If I don't explicitly map a column in code-first EF to an existing DB, will that column still work?

别来无恙 提交于 2019-12-11 06:24:46

问题


I have the following mapping defined:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<InsuranceProvider>()
                .Map(ins => ins.Properties(p => new
                {
                    PKID_Insuance = p.Id,
                    InsuranceProvider = p.Name,
                    Address1 = p.Address.Address1,
                    Address2 = p.Address.Address2,
                    City = p.Address.City,
                    State = p.Address.State,
                    Zipcode = p.Address.Zipcode,
                })).ToTable("Insurance");

        }

The table and object both share properties such as Phone and Fax with the same name. Do I need to explicitly map those or will the fall into place magically?

Thanks.

Solution:

Sure enough the mapping I proposed did not work. Once I had it working with the .HasColumnName() method, I swapped that out for the code here and got a "the property expression.... is not valid" error. Bummer.

The scaffold "Create" in MVC 3 did, however, pull both the values I defined in the mapping as well as the ones from the Database with the shared names. Funny how that works.

It would be nice if they brought that syntax back. It seems so much cleaner for remapping large quantities of columns.


回答1:


Did this work at all what you have so far? The usual way to map properties to column names in the DB is:

modelBuilder.Entity<InsuranceProvider>()
    .Property(i => i.Name)
    .HasColumnName("InsuranceProvider");

modelBuilder.Entity<InsuranceProvider>()
    .Property(i => i.Address.Address1)
    .HasColumnName("Address1");
// assuming here that Address is a complex property, not a navigation property

// etc.

And then yes, you don't need to define a mapping for properties which have the same name as the columns in the database. This mapping will happen by convention.

Alternatively you can use the [Column("...")] attribute on the properties in your model classes (doesn't work though for complex properties, only for scalars, I think).




回答2:


It will not work. The mapping is not correct. It will create two tables because Map is used to work with inheritance mapping and entity splitting (as pointed by @Slauma in comment) so your mentioned properties will be in Insurance table and other properties + PK will be in another table.

Also your usage of Map is not correct. You must use anonymous type without specifying names of properties.

You must use approach mentioned by @Slauma.



来源:https://stackoverflow.com/questions/7505056/if-i-dont-explicitly-map-a-column-in-code-first-ef-to-an-existing-db-will-that

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!