如何在使用通用库模式时获取实体的ID c# [英] How to get ID of Entity When Using Generic Repository Pattern c#
问题描述
这里是Repository,
public class Repository< T> :IRepository< T> T:class {
protected DbContext DbContext {get;组; }
保护DbSet< T> DbSet {get;组; }
public Repository(DbContext dbContext)
{
if(dbContext == null)
throw new ArgumentNullException(dbContext);
DbContext = dbContext;
DbSet = DbContext.Set< T>();
public virtual void Add(T entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if(dbEntityEntry.State == EntityState.Detached)
{
DbSet.Attach(entity);
dbEntityEntry.State = EntityState.Added;
}
else
{
DbSet.Add(entity);
$ / code>
entity.Id doen'st在这里存在
如果您在运行时浏览代码,则会看到 然后,你的问题不在于实体框架,而在于有一个通用的存储库。您需要一种方法来返回刚刚添加的(再假设) 创建一个接口: 并让您的所有模型都从中继承。然后,将您的类型约束更改为: 然后,您可以返回 Trying to figure out how to get the Id of the recently added entity when using Generic Repository pattern. An example would be nice.
here's the Repository, entity.Id doen'st exist here If you step through your code, while running, you will see the Your problem is, then, not with entity framework, but having a generic repository. You need a way to return the (assuming again) Create an interface: and have all your models inherit from it. Then, change your type constraint to: then, you can return 这篇关于如何在使用通用库模式时获取实体的ID c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! ID
(无论你有它叫什么)属性将被添加后填充。
int ID
。
public interface IEntity
{
public int ID {get;组; }
}
public class Repository< T> :IRepository< T> T:IEnitity
entity.ID
保存后。public class Repository<T> : IRepository<T> where T : class {
protected DbContext DbContext { get; set; }
protected DbSet<T> DbSet { get; set; }
public Repository(DbContext dbContext)
{
if (dbContext == null)
throw new ArgumentNullException("dbContext");
DbContext = dbContext;
DbSet = DbContext.Set<T>();
}
public virtual void Add(T entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State == EntityState.Detached)
{
DbSet.Attach(entity);
dbEntityEntry.State = EntityState.Added;
}
else
{
DbSet.Add(entity);
}
}
}
ID
(whatever you have it called) property will be populated after adding. int ID
you just added. public interface IEntity
{
public int ID { get; set; }
}
public class Repository<T> : IRepository<T> where T : IEnitity
entity.ID
after saving.