【问题标题】:Entity framework (CTP5, Fluent API). Rename column of navigation property实体框架(CTP5、Fluent API)。重命名导航属性的列
【发布时间】:2011-01-11 17:59:42
【问题描述】:

我有两个实体:

public class Address
{
        public int Id { get; set; }
 public string FirstName { get; set; 
 public string LastName { get; set; }
}

public partial class Customer
    {
        public int Id { get; set; }
        public string Email { get; set; }
        public string Username { get; set; }

        public virtual Address BillingAddress { get; set; }
        public virtual Address ShippingAddress { get; set; }
    }

以下是映射类:

public partial class AddressMap : EntityTypeConfiguration<Address>
    {
        public AddressMap()
        {
            this.ToTable("Addresses");
            this.HasKey(a => a.Id);
        }
    }
public partial class CustomerMap : EntityTypeConfiguration<Customer>
    {
        public CustomerMap()
        {
            this.ToTable("Customer");
            this.HasKey(c => c.Id);

            this.HasOptional<Address>(c => c.BillingAddress);
            this.HasOptional<Address>(c => c.ShippingAddress);
        }
    }

生成数据库时,我的“客户”表有两列用于“BillingAddress”和“ShippingAddress”属性。他们的名字是“AddressId”和“AddressId1”。 问题:如何将它们重命名为“BillingAddressId”和“ShippingAddressId”?

【问题讨论】:

    标签: entity-framework code-first


    【解决方案1】:

    基本上,您希望在独立关联中自定义 FK 列名称,此代码将为您执行此操作:

    public CustomerMap()
    {
        this.ToTable("Customer");            
    
        this.HasOptional<Address>(c => c.BillingAddress)
            .WithMany()
            .IsIndependent().Map(m => 
            {
                m.MapKey(a => a.Id, "BillingAddressId");                    
            });
    
        this.HasOptional<Address>(c => c.ShippingAddress)
            .WithMany()
            .IsIndependent().Map(m =>
            {
                m.MapKey(a => a.Id, "ShippingAddressId");
            });            
    }
    

    【讨论】:

    • 我已经按照您的建议进行了更改。但在我最初的帖子中,我简化了模型。我的客户类还有一个包含所有地址列表的属性:“public virtual ICollection
      Addresses { get; set; }”。并且客户配置类(CustomerMap)多了一行:“this.HasMany
      (c => c.Addresses).WithMany().Map(m => m.ToTable("CustomerAddresses"));”现在我收到以下错误:“序列包含多个匹配元素”。有什么想法吗?
    • 没问题。我已经复制并粘贴了您的附加代码,通过在客户和地址之间创建新的多对多关联,它对我非常有效,因此我无法重现您的异常。您能否发布您的完整对象模型和客户端代码?
    • 当然,您可以在这里下载它nopcommerce.codeplex.com/SourceControl/list/changesets(我们正在开发新版本的 nopCommerce 购物车)。注意:您建议的解决方案(独立关联)尚未添加到源代码中。只需添加它并尝试运行单元测试
    • 好吧,您需要创建一个简单的控制台应用程序并在其中尝试我的解决方案,您会看到它完美地创建了所需的架构。但是,如果您不这样做,请不要担心,我已经为您完成了:您可以从此链接下载我的示例项目并亲自查看:cid-31fdfaaf183abb01.skydrive.live.com/…
    • Morteza,感谢您的宝贵时间。您的应用程序运行良好。我会尝试在我的模型中找到问题。虽然我仍然认为 CTP5 中存在一些错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 1970-01-01
    相关资源
    最近更新 更多