如何使用Entity Framework 4 Code FirstPOCO声明一对一关系

问题描述

您只是在寻找这样的东西吗?

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添加属性):

this.Hasrequired(u => u.Profile).HasConstraint((u, p) => u.ProfileId == p.Id);

我目前不认为可以解决此问题,但是由于我们只使用CTP4,因此我相信它会改变。如果我能说:

this.Hasrequired(u => u.Profile).WithSingle().Map(
    new StoreForeignKeyName("ProfileId"));

这样,我就不必包括ProfileId属性。也许目前可以解决这个问题,但我仍然要清晨才开始思考:)。

.Include("Profile")如果您想包含“导航属性”,也请记得打电话。

解决方法

如何使用Entity Framework 4 Code First(POCO)声明一对一关系?

我发现了这个问题(在Entity Framework
4中是一对一的关系)
,但是答案引用的文章没有用(一行代码是1-1关系,但没有提及如何定义它) )。