How to return last Added Value Primary key in Generic Repository in EF4?
i try to write a repository with Ef 4, but there is a problem. i need return last added row in database return id. for exmple: i added Name, SurName but i can not access last added primary id. My Repository is below. my request is secand usage.
using System.Data.Objects;
namespace FlyAnt.DAL.FrameWork.ApplicationDomainModel
{
public interface IDomainRepository<Tmodel> : IDisposable where Tmodel : class
{
IQueryable<Tmodel> Fetch();
IEnumerable<Tmodel> GetAll();
IEnumerable<Tmodel> Find(Func<Tmodel, bool> predicate);
Tmodel Single(Func<Tmodel, bool> predicate);
Tmodel First(Func<Tmodel, bool> predicate);
bool Add(Tmodel entity);
bool Delete(Tmodel entity);
bool Attach(Tmodel entity);
}
public class DomainRepository<TModel> : IDomainRepository<TModel> where TModel : class
{
#region IDomainRepository<T> Members
private ObjectContext _context;
private IObjectSet<TModel> _objectSet;
public DomainRepository()
{
}
public DomainRepository(ObjectContext context)
{
_context = context;
_objectSet = _context.CreateObjectSet<TModel>();
}
. . . . .
. . .
. .
.
public bool Delete(Func<TModel, bool> predicate)
{
IEnumerable<TModel> records = from x in _objectSet.Where<TModel>(predicate) select x;
foreach (TModel record in records)
_objectSet.DeleteObject(record);
return SaveChanges()>0;
}
public bool Add(TModel entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
_objectSet.AddObject(entity);
return SaveChanges()>0;
}
...............
..........
......// do someting
SECAND USAGE:how can i return last added or last deleted ID?i try to make below :(
public bool Delete(Func<TModel, bool> predicate)
{
IEnumerable<TModel> records = from x in _objectSet.Where<TModel>(predicate) select x;
foreach (TModel record in records)
_objectSet.DeleteObject(record);
return _objectset.LASTDELETEDPrimaryKEY;
}
public bool Add(TModel entity)
{
if (entity == null)
throw n开发者_运维知识库ew ArgumentNullException("entity");
_objectSet.AddObject(entity);
return _objectset.LASTADDEDPrimaryKEY;
}
Best Regards...
soon you do SaveChanges()
all will be right there to use.
public int Add(TModel entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
_objectSet.AddObject(entity);
SaveChanges();
return entity.mytable_id;
}
if you want to add, let's say values to to tables and one depends on the other, let's assume:
[Table1] [Table2]
t1_id PK ts_id PK
t2_id FK name
name
you can easily:
public void Add(TModel entity1, TModel entity2)
{
if (entity1 == null || entity2 == null)
throw new ArgumentNullException("entity");
entity1.Table2 = entity2;
_objectSet1.AddObject(entity1);
_objectSet2.AddObject(entity2);
SaveChanges();
}
精彩评论