Reputation: 981
I have the following service operation in WCF 4:
public void InsertUsers(IEnumerable<User> Users)
{
using (LaCalderaEntities Context = new LaCalderaEntities())
{
UserBL UserBl = new UserBL(Context);
UserBl.InsertUsers(Users);
Context.SaveChanges();
}
}
The operation works as expected and adds a list of users to the database, but I want to know the best way to get back all the UserId's (Identity column) from the objects.
If the UserId property is being set at the server by EF when doing SaveChanges() should get back to the client automagically?
Upvotes: 1
Views: 625
Reputation: 981
I find my answer in another SO question. WCF supports ref modifier in parameters, so this would work and update the source User list at the client.
public void InsertUsers(ref IEnumerable<User> Users)
{
using (LaCalderaEntities Context = new LaCalderaEntities())
{
UserBL UserBl = new UserBL(Context);
UserBl.InsertUsers(Users);
Context.SaveChanges();
}
}
But I don't like this solution, I'm going for Andrew solution, returning the list of objects from the method.
Upvotes: 0
Reputation: 1125
Well The User Objects That you sent in to get update will have the ID Attached after save.
your service could return a Int[] of ID's instead if being a void Method. However you wouldn't know what ID was associated with what user.
public int[] InsertUsers(IEnumerable<User> Users)
{
using (LaCalderaEntities Context = new LaCalderaEntities())
{
UserBL UserBl = new UserBL(Context);
UserBl.InsertUsers(Users);
Context.SaveChanges();
//At This Point Your Users objects have ID's
return Users.Select(u=>u.ID).ToArray()
}
}
If all you need are the ID's then that would work
Upvotes: 0
Reputation: 40150
EF automatically updates the key properties with their generated values. You can simply access those properties from the POCOs
public void InsertUsers(IEnumerable<User> Users)
{
using (LaCalderaEntities Context = new LaCalderaEntities())
{
UserBL UserBl = new UserBL(Context);
UserBl.InsertUsers(Users);
Context.SaveChanges();
}
foreach (var user in Users)
{
Console.Writeline(user.id);
}
}
Upvotes: 1