Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining data annotation using DbContext versus Objectcontext in the database first approach

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

like image 442
John John Avatar asked Nov 20 '25 04:11

John John


1 Answers

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; }
}
like image 128
bricelam Avatar answered Nov 21 '25 19:11

bricelam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!