如果我没有将代码优先EF中的列显式映射到现有的数据块,该列是否仍然可用? [英] If I don't explicitly map a column in code-first EF to an existing DB, will that column still work?

查看:97
本文介绍了如果我没有将代码优先EF中的列显式映射到现有的数据块,该列是否仍然可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了以下映射:

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?

谢谢。

解决方案:

我提出的映射确实不起作用。一旦我使用.HasColumnName()方法,我交换了这里的代码,并得到一个属性表达式....无效的错误。 Bummer。

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.

MVC 3中的脚本创建,但是拉取了在映射中定义的值以及数据库中具有共享名称的值。有趣的是如何工作。

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.

推荐答案

将属性映射到数据库中的列名称的通常方法是:

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.

或者您可以使用 [Column(...)] 属性在你的模型类的属性(不适用于复杂的属性,仅适用于标量,我认为)。

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).

这篇关于如果我没有将代码优先EF中的列显式映射到现有的数据块,该列是否仍然可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆