使用带有继承类(每个类型一个表)的MVC脚手架存储库是行不通的

本文关键字:MVC 脚手架 行不通 存储 一个 继承 类型 | 更新日期: 2023-09-27 18:01:18

我有一个继承自UserProfile的类Tenant。我使用每个类型表的继承所以我的上下文类看起来像这样:

// 1 DbSet for superclass UserProfile
public DbSet<LetLord.Models.UserProfile> UserProfile { get; set; } 

我使用存储库类进行数据访问,并使用以下包管理器命令创建TenantRepository:

脚手架控制器租户-存储库

当我尝试运行应用程序时,tenanrepository中对Tenant的所有引用都会抛出以下错误…

MyNamespace。MyContext'不包含定义'Tenant',也没有'Tenant'的扩展名,它接受第一个参数'MyNamespace '。

…如以下引用:

public IQueryable<Tenant> All
{
    get { return context.Tenant; } // error line here
}

当使用每个类型表的继承时,应该只包括基类的DbSet,所以我理解为什么我得到错误。

在诸如我的场景中如何使用带有派生类的存储库?


编辑

当使用.Add(), .Find(), .Remove()等时,上述是如何完成的?

与前面提到的方法相同的错误:

public Tenant Find(int id)
{
    return context.UserProfile.OfType<Tenant>().Find(id); // error at .Find()
}

使用带有继承类(每个类型一个表)的MVC脚手架存储库是行不通的

试试这个:

public IQueryable<Tenant> All
{
    get { return context.UserProfile.OfType<Tenant>(); }
}

这将只返回租户。

对于其他方法,如添加,查找,删除:

public Tenant Find(int id)
{
    // a few different options here -- assumes your key property is Id
    return context.UserProfile.OfType<Tenant>().SingleOrDefault(t => t.Id == id);
    // option 2 
    // even though your context does not expose a DbSet<Tenant>, you can still
    // use the Set<TResult>() method to get only tenants this way
    return context.Set<Tenant>().Find(id);
}
public void Add(Tenant tenant)
{
    context.Add(tenant);
}
public void Remove(Tenant tenant)
{
    context.Set<Tenant>().Remove(tenant);
}