我有一个由 ASP.NET 身份框架创建的 ApplicationUser
表,我想使用另一个具有一对一关系
的 Customer 表。 ApplicationUser
表的PK
是字符串类型的Id
。 Customer
表有一个字符串类型的 FK
。我不允许更改 ApplicationUser
表的 Id
类型。但是客户表必须有一个 int 类型的标识(自动编号)列。这很好。
然后这个Customer
表与Contact
表有一对多
关系。
Customer
和Contact
表都有唯一的标识列Id
。 Contact
表有一个 CustomerId
列。如果没有 AspNetUser
表,代码首先使用这些 id
和 CustomerId
列生成一对多
关系.由于 AspNetuser
表与 Customer
具有一对一
关系,因此不使用 CustomerId
。但代码首先生成自己的字符串键 (Customer_UserId)
以构建此一对多
关系。
如何使用 Customer
表列关联 Contact
表 CustomerId
列以使用 EF6 代码优先方法映射关系?
完整代码如下:
应用程序用户
public class ApplicationUser : IdentityUser
{
//Navigation properties
public Customer Customer { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
}
客户
public class Customer
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Index(IsUnique = true)]
public int Id { get; set; }
[Key, ForeignKey("ApplicationUser")]
public string UserId { get; set; }
public string BusinessName { get; set; }
//Navigation properties
[ForeignKey("UserId")]
public ApplicationUser ApplicationUser { get; set; }
public virtual ICollection<Contact> Contacts { get; set; }
}
联系方式
public class Contact
{
public int Id { get; set; }
public int CustomerId { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string OfficeLocation { get; set; }
//Navigation properties
[Required]
public Customer Customer { get; set; }
}
ApplicationDbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(): base("DefaultConnection", throwIfV1Schema: false){}
static ApplicationDbContext()
{
// Set the database intializer which is run once during application start
// This seeds the database with admin user credentials and admin role
Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Customer>()
.HasRequired(u => u.ApplicationUser).WithRequiredDependent(c => c.Customer);
}
public System.Data.Entity.DbSet<WebServer.Models.Customer> Customers { get; set; }
public System.Data.Entity.DbSet<WebServer.Models.Contact> Contacts { get; set; }
}
最佳答案
我发现删除显式外键并删除联系人的“客户”属性会显着改变架构。
这将删除 Customer_UserId
。
看起来这就是您所追求的行为。
关于c# - Entity Framework 6 Code first 3级子表中的一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32085884/