2013-03-11 40 views
1

我编码在EF 5码第一溶液和我有一个模型如下:的EntityFramework模型关系配置

public class User 
{ 
    public int Id {get;set;} 

    public int Role1Id {get; set;} 
    public Role Role1 {get; set;} 
} 

和另一种模式:

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

    public string Title {get; set;} 
} 

也i的另一配置此模型类如下:

public class UserConfig : EntityTypeConfiguration<User> 
    { 
     public UserConfig() 
     { 
      ToTable("User", "dbo"); 
      // Here i want introduce Role1 as navigation property for Role1Id property 
     } 
    } 

这里是问题:我如何配置用户模型引入Role1作为导航道具Role1Id属性?

+0

你自己在写这段代码吗?实体框架可以自己创建这个管道代码。 – rhughes 2013-03-11 12:16:20

+0

我先使用ef代码,所以我必须先编码我的模型。 – 2013-03-11 12:18:30

回答

1

您可以使用注释:只要自动标识在数据库模式中产生的磁场相匹配

public class User 
{ 
    public int Id {get;set;} 

    public int Role1Id {get; set;} 

    [ForeignKey("Role1Id")] 
    public Role Role1 {get; set;} 
} 
+0

是的,但我想在我的UserConfig类(通过实体模型配置)配置我的模型。 – 2013-03-11 12:25:50

0

EF应该配置它。

你可以尝试用下面的配置它在UserConfig的:

HasRequired(user => user.Role1) 
    .WithRequiredDependent() 
    .Map(mapping => mapping.MapKey("Role1Id"); 

此配置它是必要的。如果不需要,也可以使用HasOption方法。