2016-02-28 98 views
0

我正試圖實現與發生的事情非常相似的事情in this EF7 fluent API documentation,但事實並非如此。實體框架7 DbContext OnModelCreating爲ApplicationUser字段指定外鍵

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

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類沒有在它有關的博文什麼。因此,連接並不需要雙向進行。

有人能告訴我如何我的情況我怎麼可以告訴大家,我想用包括基於在博文中CreatedBy場平了AspNetUsers表用戶名字段時填充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。

回答

0

我想出了一個解決方案,在我的最後工作得很完美。

這是一個需要把你的DbContext文件,以獲得良好的API代碼這個工作:

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字段,我需要獲取整個用戶才能在我的視圖中顯示名字,姓氏,電子郵件等信息,我假設我會做很多事情。我可能很少需要通過用戶檢索我的任何實體的列表,但是如果我這樣做了,我會將List MyObjects添加到ApplicationUser模型,然後在.WithMany(b => b.MyObjects)參數中指定一些內容。

如果有人有任何意見或其他意見,請讓我知道。