栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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")
如果您想包含“导航属性”,也请记得打电话。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/465287.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号