实体框架4 - 定制复杂类型映射 [英] Entity framework 4 - custom complex type mapping

查看:101
本文介绍了实体框架4 - 定制复杂类型映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很差的遗留数据库模式,我正在通过EF Code First工作。我目前正在映射POCO实体,并希望创建一个地址复杂类型,并将其用于存储街道地址信息的地方。不幸的是,并不是所有的地址字段都在数据库中被命名为相同的(即一个表可能具有Address1,而另一个表将具有Street1,即使它们是相同的。



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

解决方案

是的,你可以用流畅的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; s et;}
public DbSet< Customer>客户{get;组;

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);
}
}


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?

解决方案

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");         
    }
}

这篇关于实体框架4 - 定制复杂类型映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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