繁体   English   中英

CF实体框架中使用映射的一对一关系

[英]One-to-one relationship in CF Entity Framework using mapping

我正在使用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; }
}

这是地图......

用户映射

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,而后者又有一个必需的用户实体”

UserProfile中的键的定义是必须的。

再看一遍,你需要将HasKey添加到UserMap,以便它知道哪一个是键,否则你可以执行以下操作: -

您是否可以将UserProfile更改为从User继承,然后将其添加到OnModelCreating方法

modelBuilder.Entity()ToTable( “用户配置”);

这将在数​​据库上创建一对一的关系。 我不得不用我当前的模型做到这一点以获得一对一,否则,如果你没有指定ToTable部分,它将把它们混为一个带有Discriminator列的表

马克欢呼

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM