简体   繁体   English

从 sql server 读取数据时检测到自引用循环

[英]Self referencing loop detected while reading data from sql server

I'm trying to read data from the database every second using the following code:我正在尝试使用以下代码每秒从数据库中读取数据:

public class DBChangeService : DelegatingHandler, IHostedService
{
    private Timer _timer;
    public SqlDependencyEx _sqlDependency;
    private readonly IHubContext<SignalServer> _hubcontext;
    private readonly IServiceScopeFactory _scopeFactory;
    string connectionString = "";
    public IConfiguration Configuration { get; }

    public DBChangeService(IConfiguration configuration, IHubContext<SignalServer> hubcontext, IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory;
        _hubcontext = hubcontext;
        Configuration = configuration;
        connectionString = Configuration.GetConnectionString("DefaultConnection");
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _timer = new Timer(Heartbeat, null, 0, 1000);
        return Task.CompletedTask;
    }


    public void Heartbeat(object state)
    {
         _hubcontext.Clients.All.SendAsync("SBSystemBrodcasting", SBSystemApps());

    }

    public async Task<List<SomeModel>> SBSystemApps()
    {
        var data = new List<SomeModel>();

        using (var scope = _scopeFactory.CreateScope())
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                string commandText = @"SELECT 
                        a.name as AppName,
                        a.state as AppState,
                        a.created_at as AppCreatedAt,
                        a.updated_at as AppUpdatedAt,
                        a.foundation as AppFoundation,

                        s.name as SpaceName,
                        o.name as OrgName
                    FROM
                        apps as a
                    INNER JOIN
                        spaces as s ON a.space_guid = s.space_guid
                    INNER JOIN
                        organizations as o ON s.org_guid = o.org_guid
                    where s.name = 'system' and o.name = 'system' and a.foundation = 2";

                try
                {
                    SqlCommand cmd = new SqlCommand(commandText, connection);

                    await connection.OpenAsync();
                    using (DbDataReader reader = await cmd.ExecuteReaderAsync())
                    {
                        while (await reader.ReadAsync())
                        {
                            var sqlresult = new SomeModel
                            {
                                AppName = reader["AppName"].ToString(),
                                AppState = reader["AppState"].ToString(),
                                AppCreatedAt = Convert.ToDateTime(reader["AppCreatedAt"]),
                                AppUpdatedAt = Convert.ToDateTime(reader["AppUpdatedAt"]),
                                AppFoundation = Convert.ToInt32(reader["AppFoundation"]),
                                SpaceName = reader["SpaceName"].ToString(),
                                OrgName = reader["OrgName"].ToString(),
                            };

                            data.Add(sqlresult);
                        }

                    }
                }
                finally
                {
                    connection.Close();
                }

                return data;
            }
        }
    }


    public Task StopAsync(CancellationToken cancellationToken)
    {
        //Timer does not have a stop. 
        _timer?.Change(Timeout.Infinite, 0);
        return Task.CompletedTask;
    }
}

getting following error:收到以下错误:

Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property 'task' with type 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder 1+AsyncStateMachineBox 1[System.Collections.Generic.List`1[TestApp.Models.SomeModel],TestApp.Services.DBChangeService+d__11]'. Newtonsoft.Json.JsonSerializationException:检测到类型为“System.Runtime.CompilerServices.AsyncTaskMethodBuilder 1+AsyncStateMachineBox 1[System.Collections.Generic.List`1[TestApp.Models.SomeModel],TestApp.Services”的属性“task”的自引用循环.DBChangeService+d__11]'。

I have tried almost all possible solutions I could find on StackOverflow but none are working我已经尝试了几乎所有可以在 StackOverflow 上找到的可能解决方案,但都没有奏效

In startup:在启动时:

services.AddMvc().AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });

On the header of my class, I tried using [JsonObject(IsReference = true)] but none are working for me any thoughts?在我班级的标题上,我尝试使用[JsonObject(IsReference = true)]但没有任何想法对我[JsonObject(IsReference = true)]

Model:模型:

[JsonObject(IsReference = true)]
    public partial class SomeModel
    {
        public string AppName { get; set; }
        public string AppState { get; set; }
        public DateTime AppCreatedAt { get; set; }
        public DateTime AppUpdatedAt { get; set; }
        public int AppFoundation { get; set; }
        public string OrgName { get; set; }
        public string SpaceName { get; set; }
    }
_hubcontext.Clients.All.SendAsync("SBSystemBrodcasting", SBSystemApps());

The issue is that you are calling SendAsync with a Task .问题是您正在使用Task调用SendAsync This is not how the API is designed to be used.这不是 API 的设计用途。 You should be passing through the actual payload you want to use.您应该传递要使用的实际有效负载

There are multiple ways to solve this.有多种方法可以解决这个问题。 One would be to use:一种是使用:

_hubcontext.Clients.All.SendAsync("SBSystemBrodcasting", SBSystemApps().GetAwaiter().GetResult());

although I would recommend reading this guidance about why it isn't a great idea.尽管我建议您阅读本指南,了解为什么它不是一个好主意。

Another would be to change SBSystemApps so it is synchronous (ie returns List<T> rather than Task<List<T>> .另一种方法是更改SBSystemApps使其同步(即返回List<T>而不是Task<List<T>>

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

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