Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...