EF Generic Repository get Id from new inserted generic entity

All my entities has property Id. All my tables in database has auto-generated integer identity Id as primary key.

I have generic method to Create entities.

Is there any way to get entity Id after entity inserted in to database?

   public override int Create<T>(T entity)
    {
        string entitySet = GetEntitySetName<T>();
        _context.AddObject(entitySet, entity);
        _context.SaveChanges();

        return <Id Here>; //TODO Return Id here
    }

In simple(not generic) repository i may just return Entity.Id, but how to get the same behavior in generic repository?
I may have base entity class for all entities which contains int property Id but is there any way to get it work without implementing this inheritance?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This can actually be dead simple;

// Project is is object/table, no POCO here.

var newProj = new Project();
newProj.Name = "Blah project";

var db = new AppDataContextname();

db.Projects.AddObject(newProj);

// at this point, newProj.ID is NOT set

db.SaveChanges(); // record is added to db.
// now, the ID property of the Project object is set!!!

// if the last ID in that table is '25', and you have auto-increment,
// then the object's ID property will now be 26!
Console.WriteLine(newProj.ID); // will output "26"

Racked my brain on how to get the ID back for a long time until I realized that the above code works. Works in Linq-To-SQL and EF4.

Method 2

With POCO entities, you’d have to use an interface, reflection, or dynamic.

With EntityObject entities you can read the EntityKey property.

Method 3

The solution:

 public override TR Create<T, TR>(T entity)
    {
        string entitySet = GetEntitySetName<T>();
        _context.AddObject(entitySet, entity);
        _context.SaveChanges();

        //Returns primaryKey value
        return (TR)context.CreateEntityKey(entitySet, entity).EntityKeyValues[0].Value;                       
    }

Where T: entity type, TR: entity PK type.

Method 4

 With reflection you can obtain the Id property.


public override int Create<T>(T entity)
    {
        string entitySet = GetEntitySetName<T>();
        _context.AddObject(entitySet, entity);
        _context.SaveChanges();

         var idProperty = item.GetType().GetProperty("Id").GetValue(entity,null);
         return (int)idProperty;
    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x