简体   繁体   English

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

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

I am trying to achieve something very similar to what is happening in this EF7 fluent API documentation , but it is not the exact case. 我正在尝试实现与EF7 fluent API文档中正在发生的事情非常相似的事情,但这不是确切的情况。

I have a model that looks like this: 我有一个看起来像这样的模型:

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; }
}

My ApplicationUser class does not have anything related to BlogPost in it. 我的ApplicationUser类中没有与BlogPost相关的任何内容。 So the connection doesn't really need to go both ways. 因此,连接实际上并不需要双向进行。

Can someone tell me how for my situation how I can tell entity framework that I want to populate CreatedByUser when using Include based on the CreatedBy field in BlogPost equaling the Username field in AspNetUsers table? 有人可以告诉我在我的情况下如何如何基于BlogPost中的CreatedBy字段(等于AspNetUsers表中的Username字段)使用Include时告诉实体框架我要填充CreatedByUser吗?

Here is what I want to be able to do in my repository: 这是我想要在存储库中执行的操作:

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

This is my best attempt: 这是我的最佳尝试:

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

I feel like the trick here is not adding a parameter to .WithMany() since in my model I do not have a List property inside of my ApplicationUser model. 我觉得这里的技巧不是在.WithMany()中添加参数,因为在我的模型中,我的ApplicationUser模型内部没有List属性。

The main thing that is causing me issues is that by default EF is trying to use the Id field as the key in the AspNetUsers table. 导致我出现问题的主要原因是,默认情况下,EF尝试使用Id字段作为AspNetUsers表中的键。 I want to tell it to use Username as the key, not the guid. 我想告诉它使用用户名作为键,而不是GUID。

I figured out a solution that is working perfectly on my end. 我想出了一种可以完美地解决我的问题的解决方案。

Here is the Fluent API code that needs to be put in your DbContext file in order to get this to work: 以下是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();
}

Then in my repository I can simply do the following to make sure CreatedByUser is bound: 然后,在我的存储库中,我可以简单地执行以下操作以确保CreatedByUser被绑定:

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

Here is what my models look like: 我的模型如下所示:

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; }
}

Since almost all of my objects have a CreatedBy field where I will need to obtain the entire User to be able to display things like FirstName, LastName, Email in my Views I am assuming I will be doing this a lot. 由于几乎所有对象都有一个CreatedBy字段,因此我需要获取整个User才能在视图中显示FirstName,LastName,Email之类的东西,因此我假设我会做很多事情。 I will probably rarely ever need to retrieve a list of any of my entities through the user, but if I did I would add a List MyObjects to ApplicationUser model and then specify something in the .WithMany(b => b.MyObjects) params. 我可能很少需要通过用户检索我的任何实体的列表,但是如果这样做,我会向ApplicationUser模型添加一个List MyObjects,然后在.WithMany(b => b.MyObjects)参数中指定一些内容。

If anyone has any feedback or additional comments please let me know. 如果有人有任何反馈或其他意见,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Entity Framework Core 在 OnModelCreating 中分配外键约束? - Entity Framework Core assign foreign key constraint in OnModelCreating? 实体框架不会生成ApplicationUser外键 - Entity Framework doesn't generate ApplicationUser foreign key 使用UserName作为实体框架中的外键创建ApplicationUser导航属性 - Creating an ApplicationUser navigation property using UserName as the foreign key in Entity Framework 无法在实体框架中创建ApplicationUser的外键 - Can't create foreign key to ApplicationUser in entity framework 实体框架:指定外键约束名称 - Entity Framework: Specify foreign key constraint name 在依赖注入中使用 Entity Framework Core DbContext 时不调用 OnModelCreating - OnModelCreating is not called when Entity Framework Core DbContext is used in Dependency Injection 实体框架DbContext更新值无需查询和外键 - Entity framework DbContext update value without query and by foreign key .net core 2实体框架-ApplicationUser扩展外键对象未在get上填充 - .net core 2 Entity Framework - ApplicationUser Extended Foreign Key object not populating on get 在 DbContext 中无法访问创建的实体 OnModelCreating - Entity Created OnModelCreating is not accessible in DbContext OnModelCreating Entity Framework Core - OnModelCreating Entity Framework Core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM