如何使用 Entity Framework 4 Code First (POCO) 声明一对一关系 [英] How to declare one to one relationship using Entity Framework 4 Code First (POCO)
问题描述
如何使用实体框架 4 代码优先 (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);
}
}
EDIT:是的,我面前没有 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 :).
如果你想包含一个导航属性",还记得调用 .Include("Profile")
.
Also remember to call .Include("Profile")
if you want to include a "navigational property".
这篇关于如何使用 Entity Framework 4 Code First (POCO) 声明一对一关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!