从另一个项目中的实体 类 向 ApplicationUser 添加外键

Add foreign key to ApplicationUser from entity classes in another project

我目前有一个设置,其中我的 EF6 数据库模型位于名为 Entities 的项目中。但是我有另一个名为 Infrastructure 的项目,它定义了一个 ApplicationUser class,它继承自 IdentityIUser(标准 MVC 身份验证模块)。

Infrastructure 项目知道 Entities,但反过来却不知道。我的 Web 项目只知道 Infrastructure.

我想要做的是从我的实体项目中定义的几个 classes/tables 添加一些外键引用到 ApplicationUser。我可以添加一个字段,但它只是一个标准字符串字段,没有外键约束。

这可以使用 Entity framework 吗?我试过使用 Fluent 注释,但不知道该怎么做。

我的migrations和DBContext都是在Infrastructure项目中定义的。

项目设置为:

Web
|
 Infrastructure
 | 
  Entities

我的 Web 项目不了解 Entities 项目,因为我在基础设施中有一个中间层,它为我从实体模型进行映射。

您可以将冗余的 ApplicationUser、DbSet、配置等添加到您的实体项目并在那里设置关系。然后你可以使用这样的代码:

var infrastructureUser= await UserManager.FindByIdAsync(User.Identity.GetUserId());
var entityUser = db.Users.Find(infrastructureUser.UserID);
myEntity.UserProfile = entityUser;
db.MyEntity.Add(myEntity);
await db.SaveChangesAsync();
return RedirectToAction("Index");

您也可以查看解耦 EF,但这需要大量工作。 https://jinishbhardwaj.wordpress.com/2014/07/16/decoupling-asp-net-identity-2-0-from-entity-framework-in-mvc5-part-1/