【问题标题】:How to get ID of Entity When Using Generic Repository Pattern c#使用通用存储库模式c#时如何获取实体的ID
【发布时间】:2016-10-04 20:18:13
【问题描述】:

试图弄清楚在使用通用存储库模式时如何获取最近添加的实体的 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);
        }
   }
}

entity.Id 不存在这里

【问题讨论】:

  • 当您添加实体时,其Id 属性将被填充。你应该提供一些代码。
  • 我包含了 Generic Repository 类

标签: c# generics design-patterns repository entity-framework-5


【解决方案1】:

如果您在运行时单步执行代码,您将看到添加后将填充 ID(无论您调用什么)属性。

那么,您的问题不是实体框架,而是通用存储库。您需要一种方法来返回(再次假设)您刚刚添加的int ID

创建接口:

public interface IEntity
{
    public int ID { get; set; }
}

并让您的所有模型都继承自它。然后,将类型约束更改为:

public class Repository<T> : IRepository<T> where T : IEnitity

然后,你可以在保存后返回entity.ID

【讨论】:

  • 从界面开始沿着这条路走下去,在单步执行之后,我意识到 dbcreator 没有使用 ID 作为主键,而是使用其他字段。提交后,另一个字段填充了正确的主键。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多