2

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?

axvo
  • 829
  • 2
  • 12
  • 25

1 Answers1

1

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.

Maarten
  • 22,527
  • 3
  • 47
  • 68
  • AFAIK EF does not reject an assignment itself. If underlying RDBMS is MSSQL, you could perphaps play with insert_indentity setting ([see](http://stackoverflow.com/questions/751522/how-to-change-identity-column-values-programmatically)) – pf1957 Aug 14 '14 at 09:19