首页 文章

Asp.net核心EF更新

提问于
浏览
0

我在Asp.net Core中使用了EF,但在尝试更新时遇到了以下错误 .

Microsoft.EntityFrameworkCore.dll中出现类型'System.InvalidOperationException'的异常但未在用户代码中处理附加信息:无法跟踪实体类型'TodoItem'的实例,因为具有相同键的此类型的另一个实例已经是被跟踪 . 添加新实体时,对于大多数密钥类型,如果未设置密钥,则将创建唯一的临时密钥值(即,如果为密钥属性指定了其类型的默认值) . 如果要为新实体显式设置键值,请确保它们不会与现有实体或为其他新实体生成的临时值发生冲突 . 附加现有实体时,请确保只有一个具有给定键值的实体实例附加到上下文 .

这是我的更新代码:

public class TodoRepository : ITodoRepository
{
    private readonly TodoContext _context;

    public TodoRepository(TodoContext context)
    {
        _context = context;
        //initialize database
        Add(new TodoItem { Name = "Item1" });
        //Add(new TodoItem { Name = "Item2" });
        //Add(new TodoItem { Name = "Item3" });
    }

    public IEnumerable<TodoItem> GetAll()
    {
       return _context.TodoItems.AsNoTracking().ToList();
    }

    public void Add(TodoItem item)
    {
        _context.TodoItems.Add(item);
        _context.SaveChanges();
    }

    public TodoItem Find(long key)
    {
        return _context.TodoItems.AsNoTracking().FirstOrDefault(t => t.Key == key);
    }

    public void Remove(long key)
    {
        var entity = _context.TodoItems.AsNoTracking().First(t => t.Key == key);
        _context.TodoItems.Remove(entity);
        _context.SaveChanges();
    }

    public void Update(TodoItem item)
    {
        _context.TodoItems.Update(item);
        _context.SaveChanges();
    }
}

你可以找到,我已经尝试了 AsNoTracking ,我也在Startup.cs中尝试过 .

public void ConfigureServices(IServiceCollection services)
{
    //inject repository into DI container, use database in memory
    services.AddDbContext<TodoContext>(options => options.UseInMemoryDatabase().UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking));

    //inject repository into DI container, and use sql databse
    //services.AddDbContext<TodoContext>(options=>options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));


    //The first generic type represents the type (typically an interface) that will be requested from the container. 
    //The second generic type represents the concrete type that will be instantiated by the container and used to fulfill such requests.
    services.AddSingleton<ITodoRepository, TodoRepository>();

    //add mvc service to container, this is conventional routing
    //This also applys to web api which is Attribute Routing
    services.AddMvc();
}

任何帮助,将不胜感激 .

1 回答

相关问题