【问题标题】:Entity framework 4 - custom complex type mapping实体框架 4 - 自定义复杂类型映射
【发布时间】:2011-03-16 07:11:18
【问题描述】:

我有一个写得很糟糕的遗留数据库架构,我正在通过 EF Code First 使用它。我目前正在映射 POCO 实体,并希望创建一个“地址”复杂类型,并在存储街道地址信息的任何地方使用它。不幸的是,并非所有地址字段在数据库中的名称都相同(即,一个表可能具有“Address1”,而另一个表将具有“Street1”,即使它们引用相同的东西。

有没有办法根据给定实体为复杂类型创建自定义映射?该映射是什么样的?

【问题讨论】:

  • 不要使用 CTP5。安装一个名为 4.1 RC 的新版本 - microsoft.com/downloads/en/…
  • 我认为 CTP5 是“决赛”?新版本解决了这个问题吗?
  • 不,CTP 永远不会被视为最终版本。也就是说,EF 4.1 RC 似乎比 CTP5 的根本变化更能修复错误。

标签: entity-framework-4 ef-code-first entity-framework-4.1


【解决方案1】:

是的,您可以使用 fluent API 来实现。这是一个例子:

public class User
{
    public int UserId { get; set; }   
    public Address Address { get; set; }
}

public class Customer
{
    public int CustomerId { get; set; }   
    public Address Address { get; set; }
}

[ComplexType]
public class Address
{
    public string Street { get; set; }    
    public string City { get; set; }
}

public class Context : DbContext
{    
    public DbSet<User> Users { get; set; }
    public DbSet<Customer> Customers { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {       
        modelBuilder.Entity<User>().Property(u => u.Address.Street)
                                   .HasColumnName("UserStreet");

        modelBuilder.Entity<Customer>().Property(u => u.Address.Street)
                                       .HasColumnName("CustomerStreet");         
    }
}

【讨论】:

  • 要完全保留在 FluentAPI 中,您应该删除 ComplexType 注释并使用 modelBuilder.ComplexType
    ();更新:刚刚提交了一个编辑来做到这一点,因为这是一个旧帖子......它正在等待
猜你喜欢
  • 2011-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多