I want to return the key field by doing something like this:
public virtual int InsertWithReturnId(TEntity entity)
{
dbSet.Add(entity);
return entity.Id;
}
Many thanks
EDIT #1:
I dont need a save changes... it's done like this:
public GenericRepository<Group> GroupRepository
{
get
{
if (this.groupRepository == null)
{
this.groupRepository = new GenericRepository<Group>(context);
}
return groupRepository;
}
}
My pulling (stores successfully the group)
public class GroupMethods
{
private UnitOfWork uow;
public GroupMethods() { this.uow = new UnitOfWork(); }
public int createGroup(string groupName)
{
Debug.WriteLine(groupName);
Debug.WriteLine(HttpContext.Current.User.Identity.GetUserName());
ApplicationUser user = ClanMethods.getUser(HttpContext.Current.User.Identity.GetUserName());
if(groupName != "" && user != null)
{
Debug.WriteLine("inside if");
Group grp = new Group();
grp.creator = user;
grp.Members.Add(user);
grp.GroupName = groupName;
var id = uow.GroupRepository.InsertWithReturnId(grp);
uow.Save();
Debug.WriteLine("id:"+id);
Debug.WriteLine("stops here");
Debug.WriteLine("grp id:"+grp.GroupId);
return id;
}
return 0;
}
}
I was hoping I could do grp.GroupId but it keeps failing, so I guess not. Will update on interface in 20 mins
EDIT #3
I am getting:
Warning 1 Type parameter 'TEntity' has the same name as the type parameter from outer type 'gdfinal.DAL.GenericRepository<TEntity>'
Error 2 The best overloaded method match for 'System.Data.Entity.DbSet<TEntity>.Add(TEntity)' has some invalid arguments
Error 3 Argument 1: cannot convert from 'TEntity [....\DAL\GenericRepository.cs(16)]' to 'TEntity'
Error 4 The type '...chatmodels.Group' cannot be used as type parameter 'TEntity' in the generic type or method '....GenericRepository<TEntity>.InsertWithReturnId<TEntity>(TEntity)'. There is no implicit reference conversion from '....Models.chatmodels.Group' to 'gdfinal.DAL.IIdentifier'.
when using
public virtual int InsertWithReturnId<TEntity>(TEntity entity) where TEntity : IIdentifier
{
dbSet.Add(entity);
return entity.Id;
}
It is successfully inheriting the Interface but really doesnt like it :(
Make an Interface for your EF object to use.
public interface IIdentifier
{
int Id { get; set; }
}
Then change your method (and I assume that TEntity
is a generic argument)
public virtual int InsertWithReturnId<TEntity>(TEntity entity)
where TEntity : IIdentifier
{
dbSet.Add(entity);
//save changes()?
return entity.Id;
}
If TEntity
is a generic argument on your class, then add the where
constraint to the class instead.
Now, because EF auto-generates your classes, use Partials to add the interface (in a separate file)
public partial class <NameOfObject> : IIdentifier { }
Because the class already has a property called Id
, you don't have to define it here.