![](/img/trans.png)
[英]Entity Framework Core assign foreign key constraint in OnModelCreating?
[英]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.