簡體   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