没有嵌套属性的实体框架包含 [英] Entity Framework Include without nested properties

查看:57
本文介绍了没有嵌套属性的实体框架包含的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个相关的实体,分别称为DataTag和TagSource,如下所示:

I have two related entities called DataTag and TagSource that look like the following:

public class DataTag : BaseModel
{
    [Column("DataTagId")]
    public override Guid ID { get; set; }
    public string Tag { get; set; }

    public Guid TagSourceId { get; set; }
    public TagSource TagSource { get; set; }
}

public class TagSource : BaseModel
{
    [Column("TagSourceId")]
    public override Guid ID { get; set; }
    public string Description { get; set; }
    public bool IsInternal { get; set; }
    public string Source { get; set; }

    public ICollection<DataTag> DataTags { get; set; }
}

我允许用户通过 / api / DataTags?Include = TagSource。问题是,当我包含TagSource时,它还会在该对象中包含我不希望的DataTag集合,除非用户指定(例如, / api / DataTags?Include = TagSource.DataTags。)要在我包含TagSource时阻止该属性被加载?我曾尝试使属性虚拟化并在全局范围内关闭延迟加载,但这没有用。我未将其标记为虚拟的原因是因为我使用的是AutoMapper,

I am allowing the user to Include the navigation properties through the url like "/api/DataTags?Include=TagSource". The problem is when I include the TagSource, it also includes the collection of DataTags in that object which I don't want unless the user specifies it (For example "/api/DataTags?Include=TagSource.DataTags". Is there any way to stop that property from being loaded when I include the TagSource? I have tried making the properties virtual and turning lazy loading off globally but that didn't work. The reason I haven't marked them virtual is because I am using AutoMapper and I only want to include the navigation properties that the user specifies.

推荐答案

首先:对我的英语表示歉意。

Firstly : Apologies for my English.

其次:我在使用代码优先的数据库模型创建外键时遇到了同样的问题: public virtual Collection< Object> Objects {get; set;}

Secondly : I had the same issue with a code first database model that creates foreign keys this way : public virtual Collection<Object> Objects {get; set;}

,我找到了一种解决方法,将属性设置器设置为私有:

and I found a workaround by setting the property setter as private:

public virtual Collection<Object> Objects {get; private set;}

然后,EF无法填充对象集合,因为使用私有集,您只能分配一个构造函数中的值。

Then the EF cannot populate the Objects collection because with a private set you can only assign a value in constructors.

这篇关于没有嵌套属性的实体框架包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆