2011-10-24 40 views
2

複雜類型的外鍵下面是創建使用EF 4.1代碼第一流利的API

public class User 
{ 
    public int Id { get; set; } 
    public string Firstname { get; set; } 
    public string Lastname { get; set; } 
    public DateTime? DateOfBirth { get; set; } 
    public string Username { get; set; } 
    public string Password { get; set; } 
    public string EmailAddress { get; set; } 

    public RoleType RoleType { get; set; } 
} 

public class Role 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

我已經角色類型複雜類型我的域實體(以acheive枚舉映射)。所以,我可以使用像context.Users.FirstOrDefault(u => u.RoleType.Value == (long)RoleTypes.Admin) RoleTypes.Admin是一個枚舉映射到角色實體

public class RoleType 
{ 
    public int Value { get; set; } 

    // And all the implicit operators to map with enum 
} 

然後我一直在使用流暢API

public class RoleTypeMapping : ComplexTypeConfiguration<RoleType> 
{ 
    public RoleTypeMapping() 
    { 
     Property(r => r.Value) 
      .HasColumnName("RoleId"); // To make sure that in RoleType property of User EF entity maps to an int column [RoleId] in database (table [Users]) 
    } 
} 

使用流暢的API創建的映射,我想在[Users]的[Users]表中創建一個外鍵關聯。[RoleId]引用[Role]。[Id]。請任何人都可以爲我提供指導,以達到這個目標

我厭倦了添加Role類型的屬性並通過fluent-api創建映射,但是EF創建了另一個列Role_Id並使其成爲外鍵。我希望現有的[RoleId]列(複雜類型)成爲外鍵

回答

3

這是不可能的。如果你想與角色表關聯中,你必須放棄你的枚舉類方法,並定義用戶實體,如:

public class User 
{ 
    public int Id { get; set; } 
    public string Firstname { get; set; } 
    public string Lastname { get; set; } 
    public DateTime? DateOfBirth { get; set; } 
    public string Username { get; set; } 
    public string Password { get; set; } 
    public string EmailAddress { get; set; } 

    public Role Role { get; set; } 
} 

所有的關係首先是不枚舉和複雜類型不能包含導航性能(以及外鍵)。