本文介绍了实体框架:与抽象类的多对多关系,是否在不查询数据库的情况下进行修改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Entity Framework,如果我具有以下模型:

With Entity Framework, if I have the following model:

class Asset {
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<AssetGroup> Groups { get; set; }
}

class AssetGroup {
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Asset> Assets { get; set; }
}

将现有资产添加到给定组中,而不必查询数据库以加载相关资产相对简单:

Adding an existing asset to a given group without having to query the database to load the asset in question is relatively straightforward:

using(var context = new MyContext()) {
    AssetGroup assetGroup = context.AssetGroups.Find(groupId);

    // Create a fake Asset to avoid a db query
    Asset temp = context.Assets.Create();
    temp.Id = assetId;
    context.Assets.Attach(temp);

    assetGroup.Assets.Add(temp);
    context.SaveChanges();
}

但是,我现在遇到的问题是我扩展了模型,因此是多种资产类型,实现为继承层次结构。在此过程中,资产类被抽象化了,因为没有特定类型的资产没有意义:

However, I now have the problem that I have extended the model so that there are multiple Asset types, implemented as an inheritance hierarchy. In the process, the Asset class has been made abstract, since an asset with no specific type makes no sense:

abstract class Asset {
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<AssetGroup> Groups { get; set; }
}

class SpecificAsset1 : Asset {
    public string OneProperty { get; set; }
}

class SpecificAsset2 : Asset {
    public string OtherProperty { get; set; }
}

问题是现在 Create() 调用将引发 InvalidOperationException ,因为无法创建抽象类的实例,这当然是有道理的。

The problem is that now the Create() call throws an InvalidOperationException because "Instances of abstract classes cannot be created", which of course makes sense.

所以,问题是,如何在不必从数据库中获取资产的情况下更新多对多关系?

So, the question is, how can I update the many-to-many relation without having to go fetch the Asset from the database?

推荐答案

您可以使用通用的方法以创建派生实体对象。

You can use the generic Create<T> method of DbSet<T> to create a derived entity object.

var temp1 = context.Assets.Create<SpecificAsset1>();

并从此处继续使用 temp1 作为存根实体就像您已经做过的那样。

and continue from here using temp1 as a stub entity the way you already did.

这篇关于实体框架:与抽象类的多对多关系,是否在不查询数据库的情况下进行修改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 10:16