简体   繁体   English

实体框架,成为实体的一部分

[英]Entity Framework, Getting part of an entity

I have an entity with one field I do not want to return sometimes. 我有一个只有一个字段的实体,有时不想返回。

I am setting it to null right now. 我现在将其设置为null。 Is there a way to specify this in the query itself instead of clearing it out like I am here? 有没有一种方法可以在查询本身中指定它,而不是像我在这里一样将其清除?

    public async Task<IQueryable<XYZXY>> GetStuff()
    {
            histories =
                _db.Stuffs
                    .Where(n => n.NationId == User.NationId)
                    .OrderBy(x => x.DateSent);
            await histories.ForEachAsync(d => d.Attachment = null);
            return histories;

    }

What you are looking for is called projection, this is what stuff do you want to project into your result set from the server. 您正在寻找的东西称为投影,这是您想要从服务器投影到结果集中的东西。

In EF projection is done by a combination of the select line of your query and any Includes which you have done. 在EF中,投影是通过查询的选择行和已完成的所有包含的组合来完成的。

If attachment is a second table accessed by a navigation property it wont be returned by your current query (IE it will be null) unless you are doing lazy loading (normally signified by the virtual keyword on the nav property eg public virtual Attachment Attachment {get;set;} ). 如果附件是导航属性访问的第二张表,除非您正在进行延迟加载(通常由nav属性上的virtual关键字表示,例如public virtual Attachment Attachment {get;set;}否则它不会由当前查询返回(IE将为null))。 public virtual Attachment Attachment {get;set;} )。 If attachment is a column projection is more complicated 如果附件是列投影则更复杂

You have 2 options, use an annonomous type eg: 您有2个选项,请使用匿名类型,例如:

_db.Stuffs
   .Where(n => n.NationId == User.NationId)
   .OrderBy(x => x.DateSent)
   .Select(x=> new { A = x.A, B = x.B .... /*Dont list attachment*/});

or reuse the existing object 或重用现有对象

_db.Stuffs
   .Where(n => n.NationId == User.NationId)
   .OrderBy(x => x.DateSent)
   .Select(x=> new Stuff { A = x.A, B = x.B .... /*Dont list attachment*/});

Do note custom projections will not be tracked so changing a property and calling save wont work. 请注意,自定义投影不会被跟踪,因此更改属性和调用保存将无法工作。

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

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