Cannot insert explicit value for identity column
I have standard CRUD template where I read Registers table including data from related tables
model is like this
public class Register
{
[Key]
[ScaffoldColumn(false)]
public int RegisterId { get; set; }
public Person Teacher { get; set; }
public Term Term { get; set; }
public Level Level { get; set; }
public List<Person> Students { get; set; }
}
so I read data
return Json(_context.Registers.Include(i=>i.Teacher).Include(i=>i.Term).Include(i=>i.Level).Include(i=>i.Students));
in Create action I simply check model and add new record.
[HttpPost]
public async Task<ActionResult> Register_Create([DataSourceRequest] DataSourceRequest request, Register item)
{
if (item != null && ModelState.IsValid)
{
await _context.AddAsync(item);
await _context.SaveChangesAsync();
}
return Json(new[] { item }.ToDataSourceResult(request, ModelState));
}
and on save I got
Cannot insert explicit value for identity column in table 'Levels' when IDENTITY_INSERT is set to OFF.
Cannot insert explicit value for identity column in table 'Persons' when IDENTITY_INSERT is set to OFF.
As I understand my item (being instance of Register class) is also have Teacher and Level properties each is a class of model Person and Level.
For some reason EF trying to insert a new record for in Person and Level tables as they exist in new item of model class "Register" but there already records in Person and Level tables as values for Teacher and Level taken from dropdowns (each binded to Person and Level tables)
Sorry if I missed some paragraph in documentation where is described approach to code situation like this
update if I simply reassign related
if (item != null && ModelState.IsValid)
{
// item.Level here is an instance of Level class model and it is assigned and valid (mean points to record in DB)
var level = await _context.Levels.SingleOrDefaultAsync(s => s.LevelId == item.Level.LevelId);
if (level != null) item.Level = level;
// Here I took from DB instance of Level and reassign item.Level property. item.Level before assigning and after "item.Level = level" if the same model. id and other fields the same
}
It does not try to insert new record to Levels table
@dvdobrovolskiy You will need to do something to tell EF that the Person and Level entities already exist and so should not be inserted. There are a number of different ways to do this. For example, you may be able to just call Attach on the root item (Register), which will mark the entire graph as unchanged, and then explicit set the new items to Added. For example:
_context.Attach(item);
_context.Entry(item).State = EntityState.Added;
A more flexible and powerful approach is to use _context.ChangeTracker.TrackGraph() which will iterate the graph for you and let you set the state of each entity. When using store generated keys, you can combine this with the IsKeySet on each entry as a way of determining whether an entity is new or not.
Also, don't use the async versions of Add. They are only there for some very low-level esoteric scenarios which almost nobody uses. Just use the normal Add method instead.
many thks. will study that
Still very confused about this
If I use _context.Attach(item); _context.Entry(item).State = EntityState.Added; instead of _context.Add(item);
I get
Cannot insert explicit value for identity column in table 'Registers' when IDENTITY_INSERT is set to OFF.
very confused. I only need to very simply add record to a table I do not need to manipulate graph or do any complicated manipulation during insert
Update I can tell EF that child object exist by doing this
item.Level= await _context.Levels.FirstOrDefaultAsync(f => f.LocationId == item.LevelsLevelId);
before adding but I find it weird ))
@dvdobrovolskiy That generally happens when you are attempting to Add an entity that already exists and has therefore already had a key value assigned.
I am definitely not. It trying to add related item. Related Item in other table, already existing in database.
In my case I adding new item to table Registers. Item is definitely new and never existed. But instance of Registers returned from view has Level property of type Level and it is an instance of Level class.
In this case EF trying to insert new Register item and Level item. But Level is already exist in database (as in my Editor Template I have dropdown choosing Level).
I can prevent this behaviour by setting Level property instance to itself by item.Level= await _context.Levels.FirstOrDefaultAsync(f => f.LevelId == item.Level.LevelId); here I find in DB item with same Id as item and set it to itself
@dvdobrovolskiy You'll need to provide a full repro. What you are describing should not happen if you first Attach the graph and then just set the state of the root to Added.
I am very sorry. I think I just misunderstanding whole thing about attaching graph. All I wanting is to inserting single row to DB
I'm struggling with this as well. I am trying to save a graph of objects to the database, specifically a batch which has many models which in turn has many jobs. Each job has a property that is a lookup table in the database. EF Core throws this error and complains as if I am trying to insert a new value into that lookup table, even though I am clearly not.
@ntimmerman Please open a new issue and post a small, runnable project/solution or complete code listing that demonstrates the behavior you are seeing.
Hi, sorry for late reply. I had to rebuild all to non memory optimized tables to move on. I will try to come up with runnable sample