如何禁用EF .net core2 api检索导航属性

时间:2018-08-30 15:32:04

标签: c# mysql entity-framework asp.net-core-2.0

我已经使用EF pomelo.entityframeworkcore.mysql创建了dbcontext和模型,我想弄清楚如何在尝试获取与其他表具有外键关系的对象时禁止上下文检索不必要的信息。 现在,该api通过外键导航返回对象及其相关对象。

例如,这是它返回的内容: enter image description here

这就是我要退还的方式: enter image description here

例如,我希望它在serviceextra停止。它是服务内的Icollection变量。因为service和extra都具有多对多关系的第三张表。

可能的原因:在检索服务后,我在函数中检索了三个对象

Service = await _context.Service.SingleOrDefaultAsync(m => m.Idservice == id);

我检索了另一个名为ServiceExtra的对象,现在服务具有serviceextra导航字段,因此我确实调用了此函数

var serviceExtras = await _context.ServiceExtra.Where(m => m.Fkservice == id).ToListAsync();

它也填充Service对象的serviceExtra内部的数据。如果我不调用此函数,则不会。

启动类:

public class Startup
{
    public Startup(IConfiguration configuration,IHostingEnvironment hostingEnvironment)
    {

        Configuration = configuration;
        HostingEnvironment = hostingEnvironment;

    }
    public  IConfiguration Configuration { get; }
    public IHostingEnvironment HostingEnvironment { get; }
    public void ConfigureServices(IServiceCollection services)
    {

        var connection = Configuration["ConnectionStrings:connection"];
        services.AddDbContext<Db_context>(options => options.UseMySql(connection));
        services.AddMvc();
        services.AddMvc().AddJsonOptions(
            options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
        );
    }


    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseMvc();

    }
}

0 个答案:

没有答案