axvo
axvo

Reputation: 839

Entity Framework auto generated Id if not set

Using EF Code First, I want to insert an entity with auto generated ID only if I haven't set its ID.

Here is the entity I want to insert :

public class ElementEntity
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }

    public int Property1{ get; set; }
    public string Property2{ get; set; }
}

and the function used to insert the data :

public static void AddEntity(int id, int prop1, string prop2)
    {
        db.Contents.Add(new ElementEntity
        {
            Id = id,
            Property1 = prop1,
            Property2 = prop2
        });
        db.SaveChanges();
    }

I'd like to have the same function but without the id parameter. If I use a such function, the Id is set to 0 automatically and an exception is thrown.

Does Entity Framework Code Fisrt allow mix generation Id behavior?

Upvotes: 2

Views: 3330

Answers (1)

Maarten
Maarten

Reputation: 22945

AFAIK it is not EF that generates the id, but the database that does (hence Database Generated Option). So it is a property of the database table that decides if the id field is generated.

Therefore, I think a mix is not possible. The database generates it, or not, but no mix.

Upvotes: 1

Related Questions