【发布时间】:2020-02-01 09:41:58
【问题描述】:
我正在使用 Asp.net MVC 核心开发一个应用程序,其中我使用如下通用接口:
public interface IRepository<TEntity, TKeyType> where TEntity : class where TKeyType : struct
{
TEntity Add(TEntity entity);
}
下面是它的实现。
public class EntityRepository<TEntity, TKeyType> : IRepository<TEntity, TKeyType> where TEntity : class where TKeyType : struct
{
protected readonly DrinkDbContext Context;
protected readonly DbSet<TEntity> DbSet;
public EntityRepository(DrinkDbContext context)
{
Context = context;
DbSet = context.Set<TEntity>();
}
public virtual TEntity Add(TEntity entity)
{
Context.Add(entity);
return entity;
}
}
此外,我正在继承 ShoppingCartRepository 中的 EntityRepository 类,如下所示:
public class ShoppingCartRepository<ShoppingCartItem, Int32> : EntityRepository<ShoppingCartItem, Int32>
where ShoppingCartItem : class where Int32 : struct
{
public ShoppingCartRepository(DrinkDbContext context) : base(context) { }
public override ShoppingCartItem Add(ShoppingCartItem entity)
{
base.Add(entity);
return entity;
}
}
并且能够在运行时查看方法中类的填充属性。请找到如下截图:
但是当尝试在编译时使用这些属性时,我无法看到这些属性。请找到如下截图。
如何访问在 Add 方法中作为参数传递的 ShoppingCartItem 的属性?
【问题讨论】:
-
虽然你的问题是半完整且可以理解的。请张贴代码以获得更清晰的信息,以便我们复制它stackoverflow.com/help/how-to-ask。我会这么说,尽管我相信您的问题在于通用约束。
-
@panoskarajohn : 请使用代码找到更新后的问题。
-
public class ShoppingCartRepository : EntityRepository<ShoppingCartItem, Int32>将您的代码更改为此。 ShoppingCartItem 被视为一个类作为一个通用变量。由于您需要特定功能,因此无需将 ShoppingCartRepository 设为通用。
标签: c# asp.net .net entity-framework generics