c#-使用映射的CF Entity Framework中的一对一关系
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c#-使用映射的CF Entity Framework中的一对一关系,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2318字,纯文字阅读大概需要4分钟。
内容图文
![c#-使用映射的CF Entity Framework中的一对一关系](/upload/InfoBanner/zyjiaocheng/677/d33aef95c2634c53a3f5c7287ec4dc5e.jpg)
我正在使用实体框架5,代码优先.
我有两个域对象(或表).第一个是用户,第二个是UserProfile.一个用户只能拥有一个配置文件,而一个配置文件仅属于一个用户.那是1-1的关系.
这是类….(我简化了代码,使之易于理解,实际上更复杂)
用户
public class User {
public virtual Int64 UserId { get; set; }
public virtual UserProfile UserProfile { get; set; }
public virtual String Username{ get; set; }
public virtual String Email { get; set; }
public virtual String Password { get; set; }
}
用户资料
public class UserProfile {
public virtual Int64 UserId { get; set; }
public virtual User User { get; set; }
public virtual Int64 Reputation { get; set; }
public virtual String WebsiteUrl { get; set; }
}
这是地图.
用户地图
public UserMap() {
this.Property(t => t.Email)
.IsRequired()
.HasMaxLength(100);
this.Property(t => t.Password)
.IsRequired()
.HasMaxLength(15);
this.Property(t => t.Username)
.IsRequired()
.HasMaxLength(15);
}
UserProfileMap
public UserProfileMap()
{
this.HasKey(t => t.UserId);
}
这是上下文…
public class TcContext : DbContext {
static TcContext () {
Database.SetInitializer(new TcContextInitializer());
}
public DbSet<User> Users { get; set; }
public DbSet<UserProfile> UserProfiles { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Configurations.Add(new UserMap());
modelBuilder.Configurations.Add(new UserProfileMap());
}
}
这是我的错误信息.
Unable to determine the principal end of an association between the types 'Tc.Domain.UserProfile' and 'Tc.Domain.User'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
我认为EF应该以这种方式自动确定关系.但这给了我上面的错误信息.我已经对此问题进行了一段时间的研究,但在我的案例中找不到很好的例证.
我的错误在哪里?或者,我应该在地图中定义某种附加关系吗?
解决方法:
我不得不修改UserMap类,如下所示
public UserMap() {
this.Property(t => t.Email)
.IsRequired()
.HasMaxLength(100);
this.Property(t => t.Password)
.IsRequired()
.HasMaxLength(15);
this.Property(t => t.Username)
.IsRequired()
.HasMaxLength(15);
this.HasOptional(t => t.UserProfile)
.WithRequired(t => t.User);
}
它基本上说:
“用户具有可选的实体UserProfile,而后者又具有必需的User实体”
必须在UserProfile中定义键.
内容总结
以上是互联网集市为您收集整理的c#-使用映射的CF Entity Framework中的一对一关系全部内容,希望文章能够帮你解决c#-使用映射的CF Entity Framework中的一对一关系所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。