简体   繁体   中英

SQL Server Entity Framework Insert Not Working

I'm using Entity Framework Code First and SQL Server in my application. In one place of my code, i tried to simply insert data into the database. I've got collection of objects like

public class DrivingStatistic
{
    public int Id { get; set; }
    public int CarId { get; set; }
    public virtual Car Car { get; set; }
    public DateTime DateFrom { get; set; }
    public DateTime DateTo { get; set; }

    public BLL.Consts.DrivingStatisticType Type { get; set; }
    public double Value { get; set; }
}

I add it to my object set by simply:

foreach(var entity in data)
    _objectSet.Add(entity);
unitOfWork.SaveChanges();

Everything works fine on my local database, but on a remote server, nothing happens. Almost nothing.

I used SQL Server Profiler and saw, that insert command was created and executed correctly, here it is

exec sp_executesql N'INSERT [dbo].[DrivingStatistics]([CarId], [DateFrom], 
  [DateTo], [Type], [Value])
  VALUES (@0, @1, @2, @3, @4)
  SELECT [Id]
  FROM [dbo].[DrivingStatistics]
  WHERE @@ROWCOUNT > 0 AND [Id] = scope_identity()',N'@0 int,@1 
  datetime2(7),@2 datetime2(7),@3 int,@4 float',@0=1000,@1='2017-08-25 
  07:00:00',@2='2017-08-25 08:00:00',@3=4,@4=0

Identity in my table was incremented, but no row was inserted. I invoked this SQL command manually via Microsoft SQL Management Studio, and everything was successfully committed to Db, but Id was a bigger number than expected, that's I know, that Identity was previously incremented.

Of course, there is no problem with inserting other entities in other parts of the code.

If anyone has seen such issue before, please advise me what could cause this problem.

Any help would be very appreciated :)

EDIT:

  • CarId is the foreign key and it is the only one dependency in this table.
  • DrivingStatisticType is an enum.
  • EntityFramework didn't throw any exception
  • Entity Framework is not trying to reinsert those rows.
  • There is nothing in SQL Server Log about those inserts

I make it to work by changing

foreach(var entity in data)
    _objectSet.Add(entity);
unitOfWork.SaveChanges();

to

foreach(var entity in data)
{
    _objectSet.Add(entity);
    unitOfWork.SaveChanges();
}

But if anyone knows why in some situation it is not possible to add multiple rows and commit them together, please tell me. I'm really curious what Was going about here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM