使用实体框架4代码优先(POCO)如何声明一对一的关系 [英] How to declare one to one relationship using Entity Framework 4 Code First (POCO)
问题描述
如何使用Entity Framework 4 Code First(POCO)声明一对一的关系?
How to declare a one to one relationship using Entity Framework 4 Code First (POCO)?
我发现这个问题(实体框架4中的一对一关系),但是文章答案引用不是有用的(有一行代码是1-1关系,但没有提到如何定义它)。
I found this question (one-to-one relationships in Entity Framework 4) , but the article that the answer references was not useful (there is one line of code that is a 1-1 relationship, but no mention of how to define it).
推荐答案
你是否只是寻找这样的东西?
Are you just looking for something like this?
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public Profile Profile { get; set; }
public int ProfileId { get; set; }
}
public class Profile
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string PostalCode { get; set; }
// etc...
}
public class UserMapping : EntityConfiguration<User>
{
public UserMapping()
{
this.HasKey(u => u.Id);
this.Property(u => u.Username).HasMaxLength(32);
// User has ONE profile.
this.HasRequired(u => u.Profile);
}
}
public class ProfileMapping : EntityConfiguration<Profile>
{
public ProfileMapping()
{
this.HasKey(p => p.Id);
this.Property(p => p.FirstName).HasMaxLength(32);
this.Property(p => p.LastName).HasMaxLength(32);
this.Property(p => p.PostalCode).HasMaxLength(6);
}
}
编辑:是的,在我面前没有VS,但是您需要在 UserMapping
中添加以下行,而不是当前的 HasRequired
并添加一个 ProfileId
属性(而不是您添加的 Profile_Id
):
EDIT: Yeah I didn't have VS in front of me but you need to add the following line in the UserMapping
instead of the current HasRequired
and also add a ProfileId
property (instead of Profile_Id
that you added):
this.HasRequired(u => u.Profile).HasConstraint((u, p) => u.ProfileId == p.Id);
我目前不认为有办法解决这个问题,但我相信会改变因为我们只在CTP4。如果我可以这样说,这将是很好:
I currently don't think there's a way around this, but I'm sure it'll change since we're only in CTP4. It'd be nice if I could say:
this.HasRequired(u => u.Profile).WithSingle().Map(
new StoreForeignKeyName("ProfileId"));
这样我不需要包含一个 ProfileId
属性。也许现在有一种方法,还有一个是清晨,我想想:)
This way I wouldn't have to include a ProfileId
property. Maybe there is a way around this currently and it's still to early in the morning for me to think :).
还记得调用。 (资料)
如果您要包含导航属性。
Also remember to call .Include("Profile")
if you want to include a "navigational property".
这篇关于使用实体框架4代码优先(POCO)如何声明一对一的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!