微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何使用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关系,但没有提及如何定义它) )。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。