簡體   English   中英

實體框架7 DbContext OnModelCreating為ApplicationUser字段指定外鍵

[英]Entity Framework 7 DbContext OnModelCreating specify foreign key for ApplicationUser field

我正在嘗試實現與EF7 fluent API文檔中正在發生的事情非常相似的事情,但這不是確切的情況。

我有一個看起來像這樣的模型:

public class BlogPost
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public string CreatedBy {get; set; }

    public ApplicationUser CreatedByUser { get; set; }
}

我的ApplicationUser類中沒有與BlogPost相關的任何內容。 因此,連接實際上並不需要雙向進行。

有人可以告訴我在我的情況下如何如何基於BlogPost中的CreatedBy字段(等於AspNetUsers表中的Username字段)使用Include時告訴實體框架我要填充CreatedByUser嗎?

這是我想要在存儲庫中執行的操作:

using (var blogContext = new BlogContext())
{
  return blogContext .BlogPosts
    .Include(bp => bp.CreatedByUser)
}

這是我的最佳嘗試:

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<BlogPost>()
        .HasOne(fp => fp.CreatedByUser)
        .WithMany()
        .HasForeignKey(fp => fp.CreatedBy)
        .IsRequired();
}

我覺得這里的技巧不是在.WithMany()中添加參數,因為在我的模型中,我的ApplicationUser模型內部沒有List屬性。

導致我出現問題的主要原因是,默認情況下,EF嘗試使用Id字段作為AspNetUsers表中的鍵。 我想告訴它使用用戶名作為鍵,而不是GUID。

我想出了一種可以完美地解決我的問題的解決方案。

以下是Fluent API代碼,需要將其放入DbContext文件中才能使其正常工作:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    // Need to do this because if using as a foreign key it must match the length of the principal key
    builder.Entity<BlogPost>()
        .Property(fp => fp.CreatedBy)
        .HasMaxLength(256);

    // A BlogPost has one CreatedByUser (notice we must specify the PrincipalKey to be UserName from the AspNetUsers table otherwise EF would attempt to use the Id (Guid) field by default)
    builder.Entity<BlogPost>()
        .HasOne(bp => bp.CreatedByUser)
        .WithMany()
        .HasForeignKey(bp => bp.CreatedBy)
        .HasPrincipalKey(u => u.UserName)
        .IsRequired();
}

然后,在我的存儲庫中,我可以簡單地執行以下操作以確保CreatedByUser被綁定:

public IEnumerable<BlogPost> GetBlogPosts()
{
    return _context.BlogPosts
    .Include(bp => bp.CreatedByUser)
    .ToList();
}

我的模型如下所示:

public class BlogPost
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    // Foreign Key
    public string CreatedBy { get; set; }
    // Navigation Property
    public ApplicationUser CreatedByUser { get; set; }
}

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

由於幾乎所有對象都有一個CreatedBy字段,因此我需要獲取整個User才能在視圖中顯示FirstName,LastName,Email之類的東西,因此我假設我會做很多事情。 我可能很少需要通過用戶檢索我的任何實體的列表,但是如果這樣做,我會向ApplicationUser模型添加一個List MyObjects,然后在.WithMany(b => b.MyObjects)參數中指定一些內容。

如果有人有任何反饋或其他意見,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM