【问题标题】:ASP.NET Core MVC: how to bind entities to a specific user using Entity FrameworkASP.NET Core MVC:如何使用实体框架将实体绑定到特定用户
【发布时间】:2021-10-26 15:07:18
【问题描述】:

我知道我的问题有点宽泛,但我没有在网上找到任何好的答案。

我正在构建一个 ASP.NET Core MVC Web 应用程序。我正在寻找有关如何将特定用户绑定到实体(模型中的类)的提示。问题实际上是关于如何将某个用户绑定到数据库中的某个实体。

任何帮助将不胜感激。

【问题讨论】:

  • 如果您的业务逻辑有限,请使用不同的操作方法。或使用类似工厂方法的方法接受参数取决于用户类型/名称
  • 请提供足够的代码,以便其他人更好地理解或重现问题。
  • 你的意思是要建立User表和其他表之间的关系吗?如果是这种情况,你可以参考RelationshipsOne-to-Many Relationship Conventions in Entity Framework CoreCustomize Identity(如果你正在使用Asp.net 核心身份)
  • 给相关实体添加一个UserId

标签: entity-framework asp.net-core asp.net-core-mvc


【解决方案1】:

ApplicationUser(或IdentityUser)与任何其他实体类一样。

例如,创建 1-n 关系如下所示:

public class ApplicationUser : IdentityUser
{
    public virtual IList<MyEntity> MyEntities { get; set; } // navigation property
}

public class MyEntity
{
    public int Id { get; set; }

    public string CreatedByUserId { get; set; }        // FK
    public ApplicationUser CreatedByUser { get; set; } // Navigation property
}

你也可以用流畅的方式做到这一点:

public class ApplicationUser : IdentityUser { }
public class MyEntity
{
    public int Id { get; set; }
    public string CreatedByUserId { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<MyEntity>(b => {
            b.HasOne<ApplicationUser>()
             .WithMany()
             .HasForeignKey(myEntity => myEntity.CreatedByUser);
        });
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多