[英]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.