实体框架4-自定义复杂类型映射

发布于 2024-10-22 02:02:48 字数 223 浏览 3 评论 0原文

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

有没有一种方法可以创建自定义映射对于基于给定实体的复杂类型,该映射是什么样的?

I have a poorly written legacy database schema that I'm working with via EF Code First. I'm currently mapping POCO entities and would like to create an "Address" complex type and use this everywhere where street address information is stored. Unfortunately, not all of the address fields are named the same in the database (ie. one table might have "Address1" while another table will have "Street1" even though they refer to the same thing.

Is there a way to create custom mappings for a complex type based on a given entity? What does that mapping look like?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

美人迟暮 2024-10-29 02:02:48

是的,您可以使用 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");         
    }
}

Yes, you can achieve that with fluent API. Here is an example:

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");         
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文