Return 基于选择的 DbSet

Return DbSet based on selection

我正在编写一个 ASP.NET 核心 MVC 网络应用程序,它是一个用于处理部件数据库的工具。我想要的是让用户 select a Part 然后它将执行一些操作,比如从它的数据库中删除该部分。但是,我希望这是所有部分都使用的通用操作。

我有一个 class 层次结构,它是:

我需要的是一些我可以调用的方法,它将获得我的部分所属的 DbSet。这是我想要做的事情的一个例子:

型号

public class Part
{
    public Nullable<int> ID { get; set; }
    public string Brand { get; set; }
}

public class PartA : Part
{
    public int Length { get; set; }
    public List<Image> Images { get; set; }
}

public class PartB : Part
{
    public int Durability { get; set; }
}

public class Image
{
    public Nullable<int> ID { get; set; }
    public string ImagePath { get; set; }
}

PartsDbContext

public class PartsDbContext : DbContext
{
    public DbSet<PartA> PartAs { get; set; }
    public DbSet<PartB> PartBs { get; set; }
}

部件控制器

public IActionResult DeletePart (string partType, int id)
{
    var partSet = GetDbSet(partType);
    var part partSet.FirstOrDefault(e => e.ID == id);

    if (part != null)
    {
        partSet.Remove(part);
        _context.SaveChanges();
    }
}

//function to find and return DbSet of the selected type
private DbSet<Part> GetDbSet (string partType)
{
    switch (partType)
    {
        case "PartA":
            return _context.PartAs;
        case "PartB":
            return _context.PartBs;
    }
    return null;
}

现在显然这是行不通的,因为编译器会抱怨:

You can't convert type DbSet<PartA> to type DbSet<Part>

有人知道我该怎么做吗?

这真的很 hacky,但有点管用。

public IActionResult DeletePart (string partType, int id)
{
    Type type = GetTypeOfPart(partType);
    var part = _context.Find(type, id);

    var entry = _context.Entry(part);
    entry.State = EntityState.Deleted;
    _context.SaveChanges();

}

但是,您真的应该只使用多态性和通用抽象控制器。

编辑您也可以为此使用显式加载。

private void LoadRelatedImages(IPart part)
{
    _context.Entry(part)
         .Collection(p => p.Images)
         .Load();

}