如何在使用通用库模式时获取实体的ID c# [英] How to get ID of Entity When Using Generic Repository Pattern c#

查看:139
本文介绍了如何在使用通用库模式时获取实体的ID c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图找出在使用Generic Repository模式时如何获得最近添加的实体的Id。一个例子会很好。
这里是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在这里存在

解决方案

如果您在运行时浏览代码,则会看到 ID (无论你有它叫什么)属性将被添加后填充。

然后,你的问题不在于实体框架,而在于有一个通用的存储库。您需要一种方法来返回刚刚添加的(再假设) int ID



创建一个接口:

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

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

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

然后,您可以返回 entity.ID 保存后。


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,

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 doen'st exist here

解决方案

If you step through your code, while running, you will see the ID (whatever you have it called) property will be populated after adding.

Your problem is, then, not with entity framework, but having a generic repository. You need a way to return the (assuming again) int ID you just added.

Create an interface:

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

and have all your models inherit from it. Then, change your type constraint to:

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

then, you can return entity.ID after saving.

这篇关于如何在使用通用库模式时获取实体的ID c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆