2

I have a problem with Entity Framework in Asp.net mvc . I want to get the Id value whenever I add a list of entities to database. How can I do this?

i use this code for add a list of entities to database :

public IEnumerable<TEntity> AddThisRange<TEntity>(IEnumerable<TEntity> entities) where TEntity : class
{
  return ((DbSet<TEntity>)this.Set<TEntity>()).AddRange(entities);
}


var Tags = _uow.AddThisRange(newTags.Select(tagName => new Tag
{
 //set properties
}));

 _uow.SaveAllChanges();

foreach (var tag in Tags)
{
   var id = tag.Id;// id always is 0
}

i using DB generated Ids (like IDENTITY in MS SQL)

testStack201541
  • 119
  • 1
  • 9

2 Answers2

3

I think the "problem" is that the id's are generated in the database. You have to first save the Tags, then fetch them again before you can use their id's in your code.

Something like this:

public IEnumerable<TEntity> AddThisRange<TEntity>(IEnumerable<TEntity> entities) where TEntity : class
{
  return ((DbSet<TEntity>)this.Set<TEntity>()).AddRange(entities);
}


var Tags = _uow.AddThisRange(newTags.Select(tagName => new Tag
{
 //set properties
}));

 _uow.SaveAllChanges();

//Pseudocode:
var savedTags = _uow.GetSavedTags(newTags);

foreach (var tag in savedTags)
{
   var id = tag.Id;// id will not be 0 anymore
}
andreasnico
  • 1,478
  • 14
  • 23
  • 1
    what is GetSavedTags? –  Mar 09 '16 at 11:39
  • Thats pseudocode for getting the tags from the database. I guess something similar exists in OP's code. – andreasnico Mar 09 '16 at 11:43
  • 1
    see my answer the problem is in the [ Select(new Tag...]. no need to reload data fromDB –  Mar 09 '16 at 11:44
  • Yeah, you actually don't need to reload the data. The `Id` will already be updated by Entity Framework automatically. `Tags` can be iterated directly, instead of `savedTags`. – vapcguy Oct 19 '18 at 14:09
0

Try this,

public TEntity Create<TEntity>()
{
   return ((DbSet<TEntity>)this.Set<TEntity>()).Create();
}

var listOfEntities =new List<Tag>();
foreach (var d in newTags)
{
    var entity = _uow.Create<Tag>();
    //set properties        
    //entity.prop=""
    listOfEntities.Add(entity);
}
_uow.AddThisRange(listOfEntities);
_uow.SaveAllChanges();

and then you can see the Id values has setted in your list

foreach (var tag in listOfEntities)
{
   var id = tag.Id;
}

you can read this article what create method is do https://msdn.microsoft.com/en-us/library/gg696136(v=vs.113).aspx