如何在ASP.NET MVC中映射许多一对多关系?

我有几个域模型 – AddressCustomerEmployeeStoreLocationAddressCustomerEmployee具有多对一关系,与StoreLocation具有一对一关系。

 public class Address { public int Id; public string Line1 { get; set; } public string Line2 { get; set; } public string Line3 { get; set; } } public class Customer { public int Id { get; set; } public string Name { get; set; } public IList
Addresses { get; set; } } public class StoreLocation { public int Id { get; set; } public string ShortCode { get; set; } public string Description { get; set; } public Address Address { get; set; } } public class Employee { public int Id { get; set; } public string Name { get; set; } public DateTime Dob { get; set; } public IList
Addresses { get; set; } }

如何映射这种关系? 我正在使用ASP.NET MVC 3.0和Entity Framework 4.1。

如果你使用代码优先(我想你想要这个,否则,你必须编辑你的Q),第一种方式是下面解释的方式:

实体:

 public class Address { [Key] public int Id { get; set; } public string Line1 { get; set; } public string Line2 { get; set; } public string Line3 { get; set; } public virtual Customer Customer { get; set; } public virtual StoreLocation StoreLocation { get; set; } public virtual Employee Employee { get; set; } public int? CustomerId { get; set; } public int? EmployeeId { get; set; } } public class Customer { [Key] public int Id { get; set; } public string Name { get; set; } public virtual ICollection
Addresses { get; set; } } public class StoreLocation { [Key] public int Id { get; set; } public string ShortCode { get; set; } public string Description { get; set; } public virtual Address Address { get; set; } } public class Employee { [Key] public int Id { get; set; } public string Name { get; set; } public DateTime Dob { get; set; } public virtual ICollection
Addresses { get; set; } }

DbContextinheritance了类:

 public class ManyOneToManyContext : DbContext { static ManyOneToManyContext() { Database.SetInitializer(new ManyOneToManyInitializer()); } public DbSet
Addresses { get; set; } public DbSet Customers { get; set; } public DbSet StoreLocations { get; set; } public DbSet Employees { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove(); modelBuilder.Entity().HasMany(c => c.Addresses).WithOptional(a => a.Customer).HasForeignKey(a => a.CustomerId); modelBuilder.Entity().HasRequired(s => s.Address).WithOptional(a => a.StoreLocation).Map(t => t.MapKey("AddressId")); modelBuilder.Entity().HasMany(e => e.Addresses).WithOptional(a => a.Employee).HasForeignKey(e => e.EmployeeId); } }

上下文初始化器:

 public class ManyOneToManyInitializer : DropCreateDatabaseAlways { protected override void Seed(ManyOneToManyContext context) { } } 

这将在下面创建db-schema: 许多一对多的关系 如果您对任何部分有任何疑问或需要澄清,请与我们联系。