Reputation: 578
couldn't think of any better title for my question, but the situation is really simple: I have my database (created using code first migration), I have my entity, it has two fields that has index contraint so I cannot insert duplicate records when those fields are same.
public class Entity
{
public int Id;
[Index("IndexName"), IsUnique = true, Order = 0]
[MaxLength(50)]
public string Name;
[Index("IndexName"), IsUnique = true, Order = 1]
public Guid CustomId;
}
For a short entity class example I made this (mine looks with more properties, getters, setters ;) )
I try to make this:
<...>
using (var ctx = new EntitiesDbContext())
{
var e1 = new Entity()
{
Name = "Bob",
CustomId = new Guid("068462F1-3557-E711-BA31-028037EC0200")
};
var e2 = new Entity()
{
Name = "Bob",
CustomId = new Guid("068462F1-3557-E711-BA31-028037EC0200")
};
ctx.Entities.Add(e1);
ctx.Entities.Add(e2);
await ctx.SaveChangesAsync(); // I get exception
}
<...>
Everything is fine, I cannot insert two records because of index, but my problem is, that it does not insert any value at all. Is it possible to make this situation, to add at least one value to DB (i.e. e1 object) ?
P.s. The problem came from more complex situation, my example is pretty obvious or stupid, but it shows the idea what I want to achieve. The problem was the system performance I guess, when two records were inserted into context and then when I context tried to save it, I got an exception.
Upvotes: 0
Views: 54
Reputation: 578
What I found interesting, I can check ctx.ChangesTracker object to get entities list that are changed.
So I just did simple check for changes count and if the count was 2 for example, I made those entities state to Unchanged.
ctx.ChangeTracker.Entries().First().State = EntityState.Unchanged
This solved my problem and pain that I was dealing with for several hours.
Upvotes: 0
Reputation: 45967
In all versions of Entity Framework, whenever you execute SaveChanges() to insert, update or delete on the database the framework will wrap that operation in a transaction.
Source: https://msdn.microsoft.com/en-us/library/dn456843(v=vs.113).aspx
So you have to save every item seperatly because the behaviour of a transaction is to do no changes to your database in case of an error.
ctx.Entities.Add(e1);
ctx.SaveChanges();
ctx.Entities.Add(e2);
ctx.SaveChanges();
Upvotes: 1