[英]Entity Framework Many to Many List Table Association
我有以下类(我仅显示重要的属性):
public class TypeLocation
{
[Key]
public int Id {get; set;}
public string Country {get; set;}
public string State {get; set;}
public string County {get; set;}
public string City {get; set;}
public List<Offer> Offers {get; set; }
public TypeLocation()
{
this.Offers = new List<Offer>();
}
}
public class Offer
{
public int Id { get; set; }
public ICollection<TypeLocation> LocationsToPublish { get; set; }
}
这将在数据库中创建以下内容:
我的问题/问题
TypeLocations
表预先填充有国家/州/县/市/市记录的静态列表,其中一个或多个可以与LocationsToPublish
属性中的Offer关联。 当我尝试使用以下代码添加位置时,Entity Framework将在TypeLocation
表中添加NEW记录,然后通过在OfferTypeLocations
表中添加记录来进行OfferTypeLocations
。
public static bool AddPublishLocation(int id, List<TypeLocation> locations)
{
try
{
using (AppDbContext db = new AppDbContext())
{
Offer Offer = db.Offers
.Include("LocationsToPublish")
.Where(u => u.Id == id)
.FirstOrDefault<Offer>();
//Add new locations
foreach (TypeLocation loc in locations)
{
Offer.LocationsToPublish.Add(loc);
}
db.SaveChanges();
}
return true;
}
catch
{
return false;
}
}
我不想要一个新的记录添加到TypeLocations
表,只是一个关系记录创建的关联OfferTypeLocations
表。 对我在做什么错有任何想法吗?
解
感谢@Mick在下面回答,我找到了解决方案。
public static bool AddPublishLocation(int id, List<TypeLocation> locations)
{
try
{
using (AppDbContext db = new AppDbContext())
{
Offer Offer = db.Offers
.Include("LocationsToPublish")
.Where(u => u.Id == id)
.FirstOrDefault<Offer>();
//Add new locations
foreach (TypeLocation loc in locations)
{
//SOLUTION
TypeLocation ExistingLoc = db.AppLocations.Where(l => l.Id == loc.Id).FirstOrDefault<TypeLocation>();
Offer.LocationsToPublish.Add(loc);
}
db.SaveChanges();
}
return true;
}
catch
{
return false;
}
}
发生的事情是,使用现有的AppDbContext,我从TypeLocations表(在此标识为AppLocations
)中检索了一条现有记录,然后将其添加到LocationsToPublish实体中。
关键是我将使用当前的AppDbContext(与Using()语句包装在一起)进行所有工作。 此上下文之外的任何数据均纯粹是信息性的,可用于辅助AppDbContext上下文中发生的记录查找或创建。 我希望这是有道理的。
TypeLocations是从其他AppDbContext加载的,它们被视为您在方法中构造的AppDbContext中的新实体。 要解决这两个问题:
我会选择2:-
public static bool AddPublishLocation(AppDbContext db, int id, List<TypeLocation> locations)
{
try
{
Offer Offer = db.Offers
.Include("LocationsToPublish")
.Where(u => u.Id == id)
.FirstOrDefault<Offer>();
//Add new locations
foreach (TypeLocation loc in locations)
{
Offer.LocationsToPublish.Add(loc);
}
db.SaveChanges();
return true;
}
catch
{
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.