[英]EF core 3.1: should I initialize list navigation properties when using eager loading to load related entities?
[英]'When attaching existing entities, ensure that only one entity instance with a given key' when adding to list of navigation properties EF Core
我正在使用 EF Core 3.1.23 w .NET Core 3.1
解釋:
我在數據庫中存儲有關 xml 文件的信息。
Xml 文件以以下格式存儲:
<section name="NAME">
<key name="NAME" value="0" />
...
</section>
xml 文件有大約 40 個部分,每個部分有 1 - 20 個字段(鍵)
對應的數據庫類:
public class XmlKey
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public virtual XmlSection XmlSection { get; set; }
public int? XmlSectionId { get; set; }
}
public class XmlSection
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public List<XmlKey> Keys { get; set; }
}
public class XmlMapping
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public virtual XmlKey XmlKey { get; set; }
public int? XmlKeyId { get; set; }
public int Value { get; set; }
}
執行代碼:
using (DatabaseContext dbContext = new DatabaseContext())
{
//add new mappings that are not in the database
dbContext.AddRange(XmlMappings);
//create new configuration and add to list of nav props
var config = new XmlConfiguration()
{
Name = Name,
Mappings = XmlMappings.ToList()
};
//Attach vs Add? Have tried both here in every location with same result
dbContext.XmlConfigurations.Attach(config);
dbContext.SaveChanges();
}
嘗試創建新配置並向該配置添加新映射時,如果 2 個映射鍵具有相同的部分,則會產生以下錯誤:
'無法跟蹤實體類型'XmlSection'的實例,因為已經在跟蹤另一個具有鍵值'{Id:12}'的實例。 附加現有實體時,請確保僅附加一個具有給定鍵值的實體實例。
(理論)流程為 go:
但是,這會導致上述錯誤。
如何避免這種行為? 我嘗試附加、分離、加載導航道具 AsNoTracking();,添加導航道具而不是顯式設置列表,更改了數據庫上下文選項。
您創建一個新的 DatabaseContext()。 XmlMappings 中是否只有新元素。 如果您在 XmlMappings 中跟蹤了元素,則必須使用您從中加載實例的相同 DatabaseContext 來保存它們。 為了更好地分析,請顯示 XmlMappings 創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.