C# EntityFrameWork模型关系配置
我使用ef 5 code first解决方案进行编码,我有一个模型如下:C# EntityFrameWork模型关系配置,c#,entity-framework,entity-framework-5,C#,Entity Framework,Entity Framework 5,我使用ef 5 code first解决方案进行编码,我有一个模型如下: public class User { public int Id {get;set;} public int Role1Id {get; set;} public Role Role1 {get; set;} } public class UserConfig : EntityTypeConfiguration<User> { public UserConfi
public class User
{
public int Id {get;set;}
public int Role1Id {get; set;}
public Role Role1 {get; set;}
}
public class UserConfig : EntityTypeConfiguration<User>
{
public UserConfig()
{
ToTable("User", "dbo");
// Here i want introduce Role1 as navigation property for Role1Id property
}
}
还有另一种模式:
public class Role
{
public int Id { get; set;}
public string Title {get; set;}
}
我还在另一个类中配置此模型,如下所示:
public class User
{
public int Id {get;set;}
public int Role1Id {get; set;}
public Role Role1 {get; set;}
}
public class UserConfig : EntityTypeConfiguration<User>
{
public UserConfig()
{
ToTable("User", "dbo");
// Here i want introduce Role1 as navigation property for Role1Id property
}
}
public类UserConfig:EntityTypeConfiguration
{
公共用户配置()
{
ToTable(“用户”、“dbo”);
//这里我想介绍Role1作为Role1Id属性的导航属性
}
}
问题是:如何配置用户模型以将Role1作为Role1Id属性的导航属性引入?您可以使用注释:
public class User
{
public int Id {get;set;}
public int Role1Id {get; set;}
[ForeignKey("Role1Id")]
public Role Role1 {get; set;}
}
您可以使用注释:
public class User
{
public int Id {get;set;}
public int Role1Id {get; set;}
[ForeignKey("Role1Id")]
public Role Role1 {get; set;}
}
只要id与数据库模式中生成的字段匹配,EF就应该自动配置它 您可以尝试在UserConfig中使用以下内容对其进行配置:
HasRequired(user => user.Role1)
.WithRequiredDependent()
.Map(mapping => mapping.MapKey("Role1Id");
这将其配置为必需的。如果不需要,也可以使用haspoption方法。EF应该自动配置它,只要id与数据库架构中生成的字段匹配 您可以尝试在UserConfig中使用以下内容对其进行配置:
HasRequired(user => user.Role1)
.WithRequiredDependent()
.Map(mapping => mapping.MapKey("Role1Id");
这将其配置为必需的。如果不需要,您也可以使用haspoption方法。您是自己编写这段代码的吗?实体框架可以自己创建这个管道代码。我先使用ef代码,所以我必须先编写我的模型。你自己写这个代码吗?实体框架可以自己创建这个管道代码。我先使用ef代码,所以我必须先编写模型。是的,可以,但我想在UserConfig类中配置模型(通过实体模型配置)。是的,可以,但我想在UserConfig类中配置模型(通过实体模型配置)。