How to define a custom naming convention if EF 5

2019-04-29 11:10发布

问题:

Suppose that I have a database with 1 table named Products. So, I go through the Db First approach and create an EF model in VS 2012 with pluralize and singularize option.

So, the model creates a Product entity for me, and default naming convention maps this entity to the dbo.Products table.

Now I want to change this behavior. In fact I want to create a custom convention to map ProductModel entity to the dbo.Products table.

Is this possible?! If so, how?

Update: My goal to do it...

As you know, whenever you update your model from database, if it causes a change in your model, the auto-generated entities will be over written.

From the other hand, I want to add data annotation attributes to entity properties so that I can use them to shape my views and want to simply work with my DbContext like the following insert:

public ActionResult Create(Product product)
    {
        if (ModelState.IsValid)
        {
            db.Products.Add(product);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(product);
    }

the problem is that my application analysis isn't completed and the database changes times to times. So, I need to update the model from the database and after that, all my attributes will removed.

So I decided to create a ProductModel class and copy the Product codes to it, and pass it the views as view model. Then, whene I want to query my db, I'll get an exception which says that the dbo.ProductModels name is not exist in the db...

Thanks in advance

回答1:

By default, a database-first approach will always map a table name to an entity of the same name (possibly pluralized/singularized). There is currently no provision in EF to tweak that by conventions or tooling. You can change/adapt/customize your model - but if you regenerate it, those changes are lost. I'm not aware of any tools/scripts/hacks to somehow "preserve" those changes and re-apply them after regenerating the model from the database.

If you need to extend the generated I'd suggest using the fact that those are partial classes - you can extend the generated class in a second physical file :

Write this in a separate file, e.g. ProductExtension.cs:

public partial class Product
{
   // add your custom methods etc. here
}

Those various files that make up that class will be merged together into one class by the C# compiler for you.

If you need to add data annotations to existing generated classes, you can use the MetadataType(..) attribute as shown in this SO question and its answers:

Write this in a separate file, e.g. ProductExtension.cs:

[MetadataType(typeof(ProductMetaData))]
public partial class Product
{
}

and then define the metadata/data annotations for your products class in yet another file, ProductMetadata.cs, like this:

public class ProductMetaData
{
    [Required]
    public int RequestId {get;set;}
    //...
}