ASP.NET MVC4:如何创建查找表,以便条目不重复



vir我正试图在我的ASP中创建一个查找表。NET MVC4应用程序,实体框架代码优先。这是我们的位置,应该有两个条目。我需要有一些与他们相关联的ID,这样就有一个LocationID存储在我的软件表中。但是,当我创建它们时,软件表中的每一行都要创建一个条目。

这是我的软件类:

public class Software
{
public int Id { get; set; }
public virtual List<SoftwareType> SoftwareTypes { get; set; }
public virtual List<Location> Locations { get; set; }
public virtual List<SoftwarePublisher> Publishers { get; set; }
[Required]
[StringLength(128)]
public string Title { get; set; }
[Required]
[StringLength(10)]
public string Version { get; set; }
[Required]
[StringLength(128)]
public string SerialNumber { get; set; }
[Required]
[StringLength(3)]
public string Platform { get; set; }
[StringLength(1000)]
public string Notes { get; set; }
[Required]
[StringLength(15)]
public string PurchaseDate { get; set; }
public bool Suite { get; set; }
public string SubscriptionEndDate { get; set; }
//[Required]
//[StringLength(3)]
public int SeatCount { get; set; }
}

这是我的位置类:

public class Location
{
public int Id { get; set; }
[Required]
[StringLength(20)]
public string LocationName { get; set; }
public virtual Software Software { get; set; }
}

这是我对种子方法的Global.asax调用:

Database.SetInitializer(new SampleData());
using (var context = new Context())
{
context.Database.Initialize(true);
}

这是我的背景:

public class Context : DbContext
{
public DbSet<Software> Software { get; set; }
public DbSet<Location> Locations { get; set; }
public DbSet<SoftwarePublisher> SoftwarePublishers { get; set; }
public DbSet<SoftwareType> SoftwareTypes { get; set; }
public Context()
{
Configuration.ProxyCreationEnabled = false;
}
}

这是我的种子:

public class SampleData : CreateDatabaseIfNotExists<Context>
{
protected override void Seed(Context context)
{
new List<Software> {
new Software { 
Title = "Adobe Creative Suite", 
Version = "CS6", 
SerialNumber = "1234634543", 
Platform = "Mac", 
Notes = "Macs rock!", 
PurchaseDate = "2012-12-04", 
Suite = true, 
SubscriptionEndDate = null, 
SeatCount = 0, 
SoftwareTypes = new List<SoftwareType> 
{ new SoftwareType { Type="Suite" }}, 
Locations = new List<Location> 
{ new Location { LocationName = "Paradise" }},
Publishers = new List<SoftwarePublisher> 
{ new SoftwarePublisher { Publisher = "Adobe" }}},
...other similar rows...
}.ForEach(s => context.Software.Add(s));
base.Seed(context);
context.SaveChanges(); 
}

因为我正在为"位置"之类的东西创建一个新列表(我需要修复SoftwareType和Publisher之类的其他东西,但让我们专注于"位置"),所以它在我的"位置"表中创建了一个新行。我如何重组我的类,以便在"位置"表中有两个条目,然后在"软件"表中的ID指向这两个条目中的一个?请记住,我是一个实体框架的新手,所以请尽量明确。谢谢

我认为您想要软件和位置之间的多对多关系。为此,您需要创建一个联接表(也称为链接表)。我相信你想在你的OnModelCreating覆盖中做到这一点

this.HasMany(i => i.Softwares)
.WithMany(c => c.Locations)
.Map(mc =>
{
mc.MapLeftKey("SoftwareId");
mc.MapRightKey("LocationId");
mc.ToTable("SoftwareLocations");
});

我从的博客文章中得到了这个片段

最新更新