Enity Framework overriding identity column

故事扮演 提交于 2020-01-11 10:06:08

问题


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.

  1. 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.
  2. 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).
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!