gpt4 book ai didi

c# - EF Core 添加相关实体(通用存储库)

转载 作者:行者123 更新时间:2023-11-30 21:40:40 30 4
gpt4 key购买 nike

我有一个具有以下模型和一对多关系的 EF Core Db

public class AttributeType
{
public int AttributeTypeId { get; set; }
public string Name { get; set; }

public List<Attribute> AttributeList { get; set; }
}

public class Attribute
{
public int AttributeId { get; set; }
public string Name { get; set; }

public int AttributeTypeId { get; set; }
public AttributeType AttributeType { get; set; }
}

如果我尝试以这种方式添加属性,它会起作用:

using (var db = new SampleDbContext())
{
var attributeType = db.AttributeTypes.FirstOrDefault();

Attribute attribute = new Attribute
{
Name = "bbb",
AttributeTypeId = attributeType.AttributeTypeId,
AttributeType = attributeType
};
var item = db.Attributes.Add(attribute);
db.SaveChanges();
}

(实际上,attributeType 将来自组合框,名称来自文本框,但现在让我们保持代码简单)

但是当我尝试使用通用方法时,如下面的代码不起作用

     AttributeType attributeType;

using (var db = new SampleDbContext())
{
attributeType = db.AttributeTypes.FirstOrDefault();
}

Attribute attribute = new Attribute
{
Name = "eee",
AttributeType = attributeType,
AttributeTypeId = attributeType.AttributeTypeId
};

DbService.Insert(attribute);

public static bool Insert<T>(T item) where T : class
{
try
{
using (var db = new SampleDbContext())
{
db.Add(item);
db.SaveChanges();
}
return true;
}
catch (Exception exception)
{
Debug.WriteLine($"DbService Insert Exception: {exception}");
return false;
}

我得到以下异常

Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateException' in Microsoft.EntityFrameworkCore.dll DbService Insert Exception: Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> Microsoft.Data.Sqlite.SqliteException: SQLite Error 19: 'UNIQUE constraint failed: AttributeTypes.AttributeTypeId'. at Microsoft.Data.Sqlite.Interop.MarshalEx.ThrowExceptionForRC(Int32 rc, Sqlite3Handle db) at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior) at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, String executeMethod, IReadOnlyDictionary2 parameterValues, Boolean closeConnection)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary
2 parameterValues) at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection) --- End of inner exception stack trace --- at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(Tuple2 parameters)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList
1 entriesToSave) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess) at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess) at UwpSamples.Services.DbService.Insert[T](T item)

但是如果我不传递 AttributeType 或者我将它设置为 null,就像下面的代码一样,它会起作用:

AttributeType attributeType;

using (var db = new SampleDbContext())
{
attributeType = db.AttributeTypes.FirstOrDefault();
}

Attribute attribute = new Attribute
{
Name = "ddd",
AttributeType = null,
AttributeTypeId = attributeType.AttributeTypeId
};

DbService.Insert(attribute);

-

AttributeType attributeType;

using (var db = new SampleDbContext())
{
attributeType = db.AttributeTypes.FirstOrDefault();
}

Attribute attribute = new Attribute
{
Name = "ddd",
AttributeTypeId = attributeType.AttributeTypeId
};

DbService.Insert(attribute);

谢谢

最佳答案

您正在实例化两个独立的上下文。一个是您检索 AttributeType 的位置,存储库中执行插入的第二个上下文将遍历实体并认为 AttributeType 是新的并尝试插入它。我建议每个请求使用一个上下文(假设这是在网络请求之后)。有一些变通方法涉及将实体标记为未更改,但您每次都必须重复该变通方法,并且它对每个模型都非常具体。

通常,您要么使用容器或 IoC 框架为每个请求检索上下文,要么在存储库的构造函数中传递上下文。通过这种方式,您可以跨不同的存储库进行多次调用,并且更改跟踪将在调用之间进行。它还简化了在对不同存储库的调用之间打开事务范围的场景。

关于c# - EF Core 添加相关实体(通用存储库),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44395395/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com