Defining data annotation using DbContext versus Ob

2019-04-11 13:29发布

问题:

I am using the database first approach with entity framework, when i used to work on the default template the database tables were mapped using the ObjectContext, so i used to create #partial classes & [MetadataType(typeof ) to apply the data annotation ,, but when i start using the Dbcontext code generation template to map the database tables i found that it will create .tt folder in my Model area were i find that i can apply the data annotation directly to the .cs classes themselves without the need to create partial classes as in objectcontext case. Currently the data annotations are working fine,, but would my approach cause me problems i am not aware of and i should create partial classes as i used to do with the Objectcontext ? BR

回答1:

In general, you shouldn't edit generated code because changes you make will be overwritten on re-generation. This is why most generators emit partial classes.

The best practice for your situation would be to create a new file in your solution with another partial class declaration. In that file, add the MetadataType attribute to the class, and add your property-level validation attributes to the "buddy" class (the one referenced in the attribute). This allows you to use validation attributes on the generated properties and, should your model/database change, you can still re-generate your model classes without losing them.

For example, your new file might look something like:

[MetadataType(typeof(PersonMetadata))]
partial class Person
{
    // Add logic to the generated class in here.

    public string FullName
    {
        get { return FirstName + " " + LastName; }
    }
}

class PersonMetadata
{
    // Add attributes to the generated properties in here.

    [Required]
    public string FirstName { get; set; }
}


回答2:

Create the same partial classes to define your metadata OR you can simply reverse engineer your existing database using the Entity Framework Power Tools so you have POCO classes. Then you can use the fluent API (you'll see the validations it adds for you) instead of data annotations to give you server side validation.

If you want client side, then you can still apply them to your models, as they wont be regenerated every time you compile .

however - I would recommend you create ViewModels and use AutoMapper to map between your EF objects and viewmodels. Then you can apply your annotations directly to your ViewModels.



回答3:

My understanding of your situation is that you reverse-engineered your Database-First style to a Code-First style. If your context class inherits from DbContext, you are in Code-First style now (unless there is some strange hybrid possible, which I don't know about!).

In code-first, there is really no point of creating partial classes for data annotations, IMO.