问题
I have a Code First EF class like so:
public class Event
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
/* snip */
}
and what I want to happen is when the ID property is null or 0 the database will generate an ID value for it, however if I explicitly set this value so newEvent.ID=10000000, it will use that as the ID column, currently doing that will result in the next available ID.
回答1:
To start, I am not aware of a good solution for this. I recommend you rethink what you are trying to do, or explain further why you need to do this. There's probably a better solution. The only solution I know of for what you want is ugly, and I can't really recommend it.
- You cannot use an identity (auto-increment) field. If you put this on your column, then there is just nothing you can do. Your database will either throw an error, or ignore values you give it.
- You will have to handle the auto-increment yourself. There are many ways to do this (store the current value in the database, perform a max() query, etc).
- You'll probably be tempted to override SaveChanges(). Here is an SO POST about that. I really do not recommend you do this either.
Perhaps someone will come along with a really awesome solution for you. Sorry, I know this was more of a non-answer for you. Good Luck.
来源:https://stackoverflow.com/questions/15315139/enity-framework-overriding-identity-column