C# 实体框架-一次插入多个复杂对象
我正在为一个网站编写一个解析器,该网站的产品与类别相关。我正试图用这些项目建立自己的数据库 我已决定使用实体框架,但我对该框架不熟悉,所以我的问题是: 在解析过程中,我有多个具有相同类别的项。但是类别是一种树。我的意思是,category有一个对parentCategory的引用 在解析过程中,我有一个类别继承列表f.e:category1->category1.1->category1.1.1 我解析并添加到数据库中的每个产品都需要验证该类别是否存在,并通过类别继承来创建不存在的类别 代码如下所示:C# 实体框架-一次插入多个复杂对象,c#,linq,entity-framework,C#,Linq,Entity Framework,我正在为一个网站编写一个解析器,该网站的产品与类别相关。我正试图用这些项目建立自己的数据库 我已决定使用实体框架,但我对该框架不熟悉,所以我的问题是: 在解析过程中,我有多个具有相同类别的项。但是类别是一种树。我的意思是,category有一个对parentCategory的引用 在解析过程中,我有一个类别继承列表f.e:category1->category1.1->category1.1.1 我解析并添加到数据库中的每个产品都需要验证该类别是否存在,并通过类别继承来创建不存在的类别 代码如下
Category parentCategory = null;
foreach (var sCategory in categories)
{
var currentCategory = d.CategorySet.SingleOrDefault(category => category.Name == sCategory && category.Parent == parentCategory);
if (currentCategory == null)
{
currentCategory = new Category(){Name = sCategory,Parent = parentCategory};
if(parentCategory != null)
d.Entry(parentCategory).State = EntityState.Unchanged;
}
parentCategory = currentCategory;
}
但在这种情况下,SingleOrDefault LinQ因异常而不工作:
Unable to create a constant value of type 'DataBaseModel.Category'. Only primitive types or enumeration types are supported in this context.
我知道我应该比较category的id,但在这种情况下,每次我向db添加sth时,它都需要将更改保存到db中
还有其他方法可以解决这个问题吗?我已经通过创建本地类别词典解决了这个问题,在使用之前,使用数据库中的数据填充这些词典
_categoriesDictionary.Clear();
foreach (var category in this.Container.CategorySet)
{
Category temp = category;
string fullCategoryString = "";
while (temp != null)
{
fullCategoryString = fullCategoryString.Insert(0, temp.Name + ";");
temp = temp.Parent;
}
_categoriesDictionary.Add(fullCategoryString, category);
}
然后在分析记录时:
Category parentCategory = null;
string fullCatString = "";
foreach (var sCategory in categories)
{
fullCatString += sCategory + ";";
Category currentCategory;
if (!_categoriesDictionary.TryGetValue(fullCatString, out currentCategory))
{
currentCategory = new Category()
{
Name = sCategory,
Parent = parentCategory
};
this.Container.CategorySet.Add(currentCategory);
_categoriesDictionary.Add(fullCatString, currentCategory);
}
parentCategory = currentCategory;
}
result.Category = parentCategory;
在我看来,这还有另一个优点:
它在开始时收集数据,然后不要每次都查询数据库