在EF中附加实体时?

时间:2017-12-03 22:11:14

标签: c# entity-framework

我在EF Core中有一个DbSet和DbContext:

public interface IMyContext : IDisposable
{
    DbSet<Order> Orders { get; set; }
    Task<int> SaveChangesAsync();
}

public class MyContext : DbContext, IMyContext
{
    public MyContext (DbContextOptions<MyContext > options) : base(options) { }

    public DbSet<Order> Orders { get; set; }

    public async Task<int> SaveChangesAsync()
    {
        return await SaveChangesAsync(CancellationToken.None);
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.EnableSensitiveDataLogging();
    }
}

public enum OrderStates
{
    Open,
    Running,
    Suspended,
    Closed,
    Cancelled
}

public class Order
{
    public int Id { get; set; }
    public int Year { get; set; }
    public int Number { get; set; }
    public int CustomerId { get; set; }
    public string CustomerDesc { get; set; }
    public OrderStates State { get; set; }
}

这里我是如何创建上下文的:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<MyContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyContext")),             services.AddHangfire(options => options.UseSqlServerStorage(Configuration.GetConnectionString("MyContext")));
    services.AddOptions();
    services.Configure<MySettings>(options => Configuration.GetSection("MySettings").Bind(options));
    services.AddMvc().AddDataAnnotationsLocalization();
    services.AddSignalR();

    services.AddSingleton<IMyContext, MyContext>();
    services.AddSingleton<Erp, Erp>(); // this references MyContext
}

当应用程序启动时,我用以下代码显示一个页面:

public class OpenOrdersModel : PageModel
{
    private readonly MyContext _context;

    public OpenOrdersModel(MyContext context)
    {
        _context = context;
    }

    public IList<Order> Orders { get; set; }

    public async Task OnGetAsync()
    {
        Orders = await _context.Orders.Where(x => x.State == OrderStates.Open).ToListAsync();
    }

    [BindProperty]
    public List<Order> ListOrders { get; set; }

    public async Task<IActionResult> OnPostAsync()
    {
        foreach (var order in ListOrders)
        {
            order.State = OrderStates.Running;
            _context.Orders.Attach(order).State = EntityState.Modified;
            await _context.SaveChangesAsync();
        }

        return RedirectToPage();
    }
}

但是当我尝试附加订单时,我收到以下错误:

  

无法跟踪实体类型“订单”的实例,因为已经跟踪了另一个键值为“Id:1002”的实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。

错误本身非常清楚,我不明白的是我如何“附加”这样一个实体。在我的所有代码中,没有 attach 指令,但上面的指令。

我不知道在哪里看,因为我真的不知道如何附上那条记录。

0 个答案:

没有答案