Сообщение EF вопрос от 25.06.2019 11:51
Изменено 25.06.2019 12:03 Kaifa
public class Product
{
[Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
public class Order
{
[BindNever]
public int OrderId { get; set; }
[BindNever]
public ICollection<CartLine> Lines { get; set; }
[Required ( ErrorMessage = "Please enter a name" )]
public string Name { get; set; }
[Required ( ErrorMessage = "Please enter first address line")]
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
[Required (ErrorMessage = "Please enter city name")]
public string City { get; set; }
[Required (ErrorMessage = "Please enter state name")]
public string State { get; set; }
public string Zip { get; set; }
[Required (ErrorMessage = "Please enter country name")]
public string Country { get; set; }
public bool GiftWrap { get; set; }
}
public class ApplicationDbContext: DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Product> Products { get; set; }
public DbSet<Order> Orders { get; set; }
}
public class EFOrderRepository : IOrderRepository
{
private ApplicationDbContext context;
public EFOrderRepository(ApplicationDbContext ctx)
{
this.context = ctx;
}
public IEnumerable<Order> Orders => context.Orders;
.Include(o => o.Lines);
.ThenInclude(p => p.Product);
public void SaveOrder(Order order)
{
context.AddRange(order.Lines.Select(l => l.Product));
if (order.OrderId == 0)
{
context.Orders.Add(order);
}
context.SaveChanges();
}
}
public class EFProductRepository: IProductRepository
{
private ApplicationDbContext context;
public EFProductRepository(ApplicationDbContext ctx)
{
this.context = ctx;
}
public IEnumerable<Product> Products => this.context.Products;
}
при выполнении context.SaveChanges() из EFOrderRepository, получается ошибка
Microsoft.EntityFrameworkCore.DbUpdateException
HResult=0x80131500
Message=An error occurred while updating the entries. See the inner exception for details.
Source=Microsoft.EntityFrameworkCore.Relational
StackTrace:
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(DbContext _, ValueTuple`2 parameters)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList`1 entries)
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 Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
at SportsStore.Models.EFOrderRepository.SaveOrder(Order order) in D:\Prj\CSharp\SportsStore\SportsStore\Models\EFOrderRepository.cs:line 30
at SportsStore.Controllers.OrderController.Checkout(Order order) in D:\Prj\CSharp\SportsStore\SportsStore\Controllers\OrderController.cs:line 33
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()
Inner Exception 1:
SqlException: Cannot insert explicit value for identity column in table 'Products' when IDENTITY_INSERT is set to OFF.
собственно пытаюсь понять, как ему сказать, чтобы первичный ключ явно не пытался вставлять? и вообще не понимаю, что он пытается делать с таблицей Products?
в профайлере выполняется
exec sp_executesql N'SET NOCOUNT ON;
INSERT INTO [Products] ([ProductID], [Category], [Description], [Name], [Price])
VALUES (@p0, @p1, @p2, @p3, @p4);
',N'@p0 int,@p1 nvarchar(4000),@p2 nvarchar(4000),@p3 nvarchar(4000),@p4 decimal(5,2)',@p0=1,@p1=N'Watersports',@p2=N'Boat for one person',@p3=N'Kayak',@p4=275.00
нафига?
public class Product
{
[Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
public class Order
{
[BindNever]
public int OrderId { get; set; }
[BindNever]
public ICollection<CartLine> Lines { get; set; }
[Required ( ErrorMessage = "Please enter a name" )]
public string Name { get; set; }
[Required ( ErrorMessage = "Please enter first address line")]
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
[Required (ErrorMessage = "Please enter city name")]
public string City { get; set; }
[Required (ErrorMessage = "Please enter state name")]
public string State { get; set; }
public string Zip { get; set; }
[Required (ErrorMessage = "Please enter country name")]
public string Country { get; set; }
public bool GiftWrap { get; set; }
}
public class ApplicationDbContext: DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Product> Products { get; set; }
public DbSet<Order> Orders { get; set; }
}
public class EFOrderRepository : IOrderRepository
{
private ApplicationDbContext context;
public EFOrderRepository(ApplicationDbContext ctx)
{
this.context = ctx;
}
public IEnumerable<Order> Orders => context.Orders
.Include(o => o.Lines)
.ThenInclude(p => p.Product);
public void SaveOrder(Order order)
{
context.AddRange(order.Lines.Select(l => l.Product));
if (order.OrderId == 0)
{
context.Orders.Add(order);
}
context.SaveChanges();
}
}
public class EFProductRepository: IProductRepository
{
private ApplicationDbContext context;
public EFProductRepository(ApplicationDbContext ctx)
{
this.context = ctx;
}
public IEnumerable<Product> Products => this.context.Products;
}
при выполнении context.SaveChanges() из EFOrderRepository, получается ошибка
Microsoft.EntityFrameworkCore.DbUpdateException
HResult=0x80131500
Message=An error occurred while updating the entries. See the inner exception for details.
Source=Microsoft.EntityFrameworkCore.Relational
StackTrace:
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(DbContext _, ValueTuple`2 parameters)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList`1 entries)
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 Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
at SportsStore.Models.EFOrderRepository.SaveOrder(Order order) in D:\Prj\CSharp\SportsStore\SportsStore\Models\EFOrderRepository.cs:line 30
at SportsStore.Controllers.OrderController.Checkout(Order order) in D:\Prj\CSharp\SportsStore\SportsStore\Controllers\OrderController.cs:line 33
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()
Inner Exception 1:
SqlException: Cannot insert explicit value for identity column in table 'Products' when IDENTITY_INSERT is set to OFF.
собственно пытаюсь понять, как ему сказать, чтобы первичный ключ явно не пытался вставлять? и вообще не понимаю, что он пытается делать с таблицей Products?
в профайлере выполняется
exec sp_executesql N'SET NOCOUNT ON;
INSERT INTO [Products] ([ProductID], [Category], [Description], [Name], [Price])
VALUES (@p0, @p1, @p2, @p3, @p4);
',N'@p0 int,@p1 nvarchar(4000),@p2 nvarchar(4000),@p3 nvarchar(4000),@p4 decimal(5,2)',@p0=1,@p1=N'Watersports',@p2=N'Boat for one person',@p3=N'Kayak',@p4=275.00
нафига?