gpt4 book ai didi

c# - 实体核心中的 IDbSet 在哪里

转载 作者:可可西里 更新时间:2023-11-01 07:53:42 26 4
gpt4 key购买 nike

enter image description here

public abstract class RepositoryBase<T> : IRepository<T> where T : class
{
private ShopCoreDbContext dbContext;
private readonly DbSet<T> dbSet; //here
protected IDbFactory DbFactory { get; private set; }
protected ShopCoreDbContext DbContext
{
get => dbContext ?? (dbContext = DbFactory.Init());
}
protected RepositoryBase(IDbFactory dbFactory)
{
DbFactory = dbFactory;
dbSet = DbContext.Set<T>();
}
public virtual T Add(T entity)
{
return dbSet.Add(entity); //err here
}
}

使用 IDbSet 没有任何反应。但是 IDbSet 接口(interface)不再存在于实体核心中。这是错误详细信息:

cannot implicitly convert type Microsoft.entityframeworkcore.changetracking.entityentry to T

要求必须是接口(interface)。
那我现在该怎么办呢?

最佳答案

解决您眼前的问题:

Add方法不直接返回实体,而是一个包装器实体。使用它的 .Entity属性取回值(或返回传入的值):

    public virtual T Add(T entity)
{
return dbSet.Add(entity).Entity;
}

关于 IDbSet<T>接口(interface):Entity Framework Core 没有 IDbSet<T>界面。

根据 this GitHub issueDbSet<T>以来没有计划将其带回现在是一个抽象基类,可用于模拟测试或子类化:

The issue with interfaces is we either exclude new members or break folks who implement the interface. The base class is also slightly better for folks writing their own test doubles (rather than using a mocking framework) since you only need to implement the methods you actually use.

[…]

Closing as we have been using the base type approach in EF6.x for a few releases now and have not heard any feedback on real scenarios where this doesn't work as well.

关于c# - 实体核心中的 IDbSet<T> 在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48363894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com