c# 类型推断 - 错误 - 没有来自的隐式引用转换

标签 c# type-inference

我有一个循环遍历 guid 列表并通过 DbContext 将它们保存到数据库的方法。 B 是 WebObject 的 DbSet 集合(例如:DbSet<MlaPerson> MlaPersons)

protected void AddRelatedWebObject<A, B>(A mlaObject, B inputObject, List<Guid> guids) 
    where A : WebObject 
    where B : DbSet<WebObject>
{
    foreach (Guid guid in guids)
    {
        mlaObject.RelatedWebObjects.Add(inputObject.Find(guid));
        _db.SaveChanges();
    }
}

用法:

foreach (ArticleRelationships item in articleRelationships)
{
    MlaArticle article = new MlaArticle();
    article = _db.MlaArticles.Include(m => m.WebSite).Where(m => m.Id == item.ArticleId).First();
    AddRelatedWebObject<MlaArticle, DbSet<MlaPerson>>(article, _db.MlaPersons, item.PersonIds);
}

_db.MlaPersons 定义为:

public class ECM2Context : DbContext
{
    public DbSet<MlaPerson> MlaPersons { get; set; }
}

MlaPerson 定义为:

public class MlaPerson : WebObject, IValidatableObject
{
    ...
}

我认为通过推断 B 是 DbSet<WebObject>会工作,因为 MlaPerson 的基类是 WebObject,但我错了。我收到错误:

The type 'System.Data.Entity.DbSet<ExternalContentManager.Models.MlaPerson>' cannot be used as a type parameter 'B' in the generic type or method 'AddRelatedWebObjects'. There is not implicit reference conversion from 'System.Data.Entity.DbSet<ExternalContentManager.Models.MlaPerson>' to 'System.Data.Entity.DbSet<ExternalContentManager.Models.WebObject>'

我非常感谢提供的任何和所有帮助。谢谢你的帮助。 B

最佳答案

你犯了一个常见的泛型错误——假设集合是协变的。即 List<Car> 的一个实例不继承自 List<Vehicle>即使汽车继承自车辆。同样,DbSet<MlaPerson>不继承自 DbSet<WebObject>尽管 MlaPerson 继承自 WebObject。

你需要做的是这样的(我没有测试过这段代码):

protected void AddRelatedWebObject<A, B, O>(A mlaObject, B inputObject, List<Guid> guids) 
    where A : WebObject 
    where B : DbSet<O>
    where O : WebObject
{
    foreach (Guid guid in guids)
    {
        mlaObject.RelatedWebObjects.Add(inputObject.Find(guid));
        _db.SaveChanges();
    }
}

并这样使用它:

foreach (ArticleRelationships item in articleRelationships)
{
    MlaArticle article = new MlaArticle();
    article = _db.MlaArticles.Include(m => m.WebSite).Where(m => m.Id == item.ArticleId).First();
    AddRelatedWebObject<MlaArticle, DbSet<MlaPerson>, MlaPerson>(article, _db.MlaPersons, item.PersonIds);
}

如果您这样做,您可以放弃类型规范 ( <MlaArticle, DbSet<MlaPerson>, MlaPerson> ),因为它应该推断它。

关于c# 类型推断 - 错误 - 没有来自的隐式引用转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7653071/

相关文章:

c# - WCF 错误 - 找不到引用契约(Contract) 'UserService.UserService' 的默认终结点元素

c# - 按其属性对通用对象列表进行分组

c# - 我不明白 EF5 dbContext.Entry(entity).Reload() 方法应该如何工作?

visual-studio-2010 - 如何让 F# 推断通用基类型?

Scala 模式匹配和类型推断

generics - 为什么是 'Code is not sufficiently generic' ?

c# - 中止与未引用对象关联的线程

generics - 当组合泛型和非泛型类时,类型变量转义作用域

c++ - 由于模板实例化导致的意外类型

c# - NSubstitute 不处理内部属性