Should I use nullable types for Id's on my Entity Objects?
My current setup:
I have an entity object with some properties, amo开发者_如何学Cng them anint Id
. To communicate with the database, I've created a repository with, among others, the following method:
public int Add(TEntity entity)
{
ObjectSet.AddObject(entity);
return entity.Id;
}
(It's a generic repository, that requires that TEntity
is a class
, and that it implements IEntity
, which is just an interface with an int Id
property.)
My problem:
Now, when I want to create a new entity for adding to the repository, I need to give it an id. However, that doesn't allow EF to automatically generate the id for me, since it will already have a value.Possible solutions:
I have only been able to think of these two possibilities.- Make the
Id
property nullable - Pass an
EntryInputModel
to the repository instead, and then do the mapping there. Currently I'm binding toEntryInputModel
in my Controller, and mapping it to anEntry
using AutoMapper. If I need to change this, I also need to re-think the dependencies in my project, since the...InputModel
and...ViewModel
classes are currently only available to my Web application.
Which is preferable? Are there more ways to counter this?
If you're using SQL Server as the backend, my recommended solution would be to make the ID column an INT IDENTITY on the database, and a not-nullable column in your entity object.
When adding a new entity, assign the ID some arbitrary value, like -1 or something, or no value at all, even. The actual ID will be generated automatically by SQL Server when you insert the new entity (
EntityContext.AddToEntities(newEntity);
EntityContext.SaveChanges();
and it will be automagically be signalled back to EF so you'll be able to use it right away once it's inserted:
int newEntityID = newEntity.ID;
Works like a charm - at least in my test apps :-)
you can have generated unique id's that are not generated by the datastore/EF, allowing you to define them before passing the object into EF... (think of Guid's)
精彩评论