gpt4 book ai didi

c# - CF Entity Framework 中使用映射的一对一关系

转载 作者:行者123 更新时间:2023-11-30 15:33:45 24 4
gpt4 key购买 nike

我正在使用 Entity Framework 5,Code-First。

我有两个域对象(或表)。第一个是 User,第二个是 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; }
}

这是 map ....

用户 map

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应该会自动判断关系。但它给了我上面的错误信息。我已经研究了这个问题一段时间,但在我的案例中找不到很好的问题说明。

我的错误在哪里?或者,我应该在 map 中定义某种附加关系吗?

最佳答案

我必须按如下方式修改 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,它又有一个必需的用户实体”

UserProfile中key的定义是必须的。

关于c# - CF Entity Framework 中使用映射的一对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16998863/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com