EF Generic Repository get Id from new inserted generic entity

后端 未结 4 1057
感动是毒
感动是毒 2020-12-19 03:30

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.

I

相关标签:
4条回答
  • 2020-12-19 04:12

    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.

    0 讨论(0)
  • 2020-12-19 04:16
     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;
        }
    
    0 讨论(0)
  • 2020-12-19 04:18

    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.

    0 讨论(0)
  • 2020-12-19 04:32

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

    With EntityObject entities you can read the EntityKey property.

    0 讨论(0)
提交回复
热议问题