简体   繁体   English

实体框架:与抽象类的多对多关系,是否在不查询数据库的情况下进行修改?

[英]Entity Framework: Many-to-Many relations with abstract classes, modify without querying database?

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; }
}

The problem is that now the Create() call throws an InvalidOperationException because "Instances of abstract classes cannot be created", which of course makes sense. 问题在于,现在Create()调用将引发InvalidOperationException因为“无法创建抽象类的实例”,这当然是有道理的。

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. 您可以使用DbSet<T>的通用Create<T>方法来创建派生实体对象。

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

and continue from here using temp1 as a stub entity the way you already did. 然后继续使用temp1作为存根实体 ,就像您已经做过的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM