2012-03-29 177 views
6

我有一個實體的Code First實體框架,目前看起來是這樣的:實體框架 - 重用複雜類型

public class Entity 
{ 
    // snip ... 

    public string OriginalDepartment { get; set; } 
    public string OriginalQueue { get; set; } 

    public string CurrentDepartment { get; set; } 
    public string CurrentQueue { get; set; } 
} 

我想創建爲這些類型的複雜類型爲這樣的事情:

public class Location 
{ 
    public string Department { get; set; } 
    public string Queue { get; set; } 
} 

我想使用相同類型的當前和原文:

public Location Original { get; set; } 
public Location Current { get; set; } 

這是可能的,或做我需要創建兩個複雜類型CurrentLocationOriginalLocation

public class OriginalLocation 
{ 
    public string Department { get; set; } 
    public string Queue { get; set; } 
} 

public class CurrentLocation 
{ 
    public string Department { get; set; } 
    public string Queue { get; set; } 
} 

回答

7

它支持開箱即用,您不需要創建兩個複雜類型。

你也可以用模型構造器明確地配置您的複雜類型

modelBuilder.ComplexType<Location>(); 

要自定義列名,您應該從父實體配置

public class Location 
{ 
    public string Department { get; set; } 
    public string Queue { get; set; } 
} 

public class MyEntity 
{ 
    public int Id { get; set; } 
    public Location Original { get; set; } 
    public Location Current { get; set; } 
} 

public class MyDbContext : DbContext 
{ 
    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.ComplexType<Location>(); 

     modelBuilder.Entity<MyEntity>().Property(x => x.Current.Queue).HasColumnName("myCustomColumnName"); 
    } 
} 

配置它們這將映射MyEntity.Current.QueuemyCustomName

+0

我想我不確定它是如何支持開箱的。 'ComplexTypeConfiguration '類有一個'Property()'方法,它要求我指定一個列名。列名將是不同的每一個 – Dismissile 2012-03-29 18:39:30

+0

我想我應該澄清,我希望能夠自定義這兩個複雜類型的列名稱。是否支持? – Dismissile 2012-03-29 18:45:01

+0

你想讓它們只有不同的前綴或完全定製? – archil 2012-03-29 18:51:49