实体框架7 DbContext OnModelCreating为ApplicationUser字段指定外键

问题描述:

我正试图实现与发生的事情非常相似的事情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。

我想出了一个解决方案,在我的最后工作得很完美。

这是一个需要把你的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)参数中指定一些内容。

如果有人有任何意见或其他意见,请让我知道。