Home > Mobile >  Entity Add/Insert with column equal to identity primary key value
Entity Add/Insert with column equal to identity primary key value

Time:12-19

During an insert/add can I make a different column equal to the newly valued primary key that's an identity auto generated value all in one write/save process? I know I can grab after fact and change but that's extra database hits I'm trying to avoid.

public class myDataTableRec
{
    public int Id { get; set; }    //This is an Identity Primary Key
    public string Name { get; set; }
    public int PostId { get; set; }  //Want this the same as Id when it gets generated
}


myrec = new myDataTableRec;
db.myDataTable.Add(myrec);
db.SaveChanges();

CodePudding user response:

You have to set the property of StoreGeneratedPattern to identity and then try you'll be able to achieve this

 myrec = new myDataTableRec;
 db.myDataTable.Add(myrec);
 db.SaveChanges();
 var id = myrec.Id;

CodePudding user response:

From https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.add?view=efcore-5.0

"Add(TEntity)

Begins tracking the given entity, and any other reachable entities that are not already being tracked, in the Added state such that they will be inserted into the database when SaveChanges() is called.

Use State to set the state of only a single entity."

Since it tracks the entity, you can do the following:

        myrec=new myDataTableRec;
        db.myDataTable.Add(myrec);
        myrec.PostId = myrec.Id
        db.SaveChanges();

Edit: If it creates the Id after the Save, the you can always create your own Id (Guid.NewGuid()) and don't let EF generate it.

CodePudding user response:

Add Key attribute to your myDataTableRec class properties. Like this:

public class myDataTableRec
{
    [Key]
    public int Id { get; set; }    
    public string Name { get; set; }
    [Key]
    public int PostId { get; set; } 
}

  • Related