ASP.NET实体框架为一对多集合返回null

时间:2018-03-19 17:47:20

标签: c# asp.net entity-framework rest

我正在尝试与以下对象建立一对多的关系。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data.Common;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;

namespace Program.Models
{
    public class Log
    {
        public int ID { get; set; }
        public string Source { get; set; }
        public string Title { get; set; }
        public DateTime Timestamp { get; set; }
        public ICollection<Category> Categories { get; set; }

        public Log()
        {
            this.Categories = new List<Category>();
        }
    }

    public class Category
    {
        public int ID { get; set; }
        public string Key { get; set; }
        public string Value { get; set; }
    }

    public class LogDBContext : DbContext
    {
        public DbSet<Log> Logs { get; set; }
        public DbSet<Category> Categories {get; set;}

        public LogDBContext(DbContextOptions<LogDBContext> options) : base(options)
        {
        }
        public LogDBContext() : base()
        {

        }
    }
}

启动时,我将以下实体放入数据库

        var cat1 = new Category { Key = "seed", Value = "seed" };
        var cat2 = new Category { Key = "seed2", Value = "seed2" };

        var log = new Log {
            Source = "seed",
                Timestamp = DateTime.Now,
                Title = "seed" };
        log.Categories.Add(cat1);
        log.Categories.Add(cat2);

        context.Logs.Add(log);

        context.SaveChanges();

我通过调用函数获取所有实体:

        [HttpGet]
        [Route("getAll")]
        public IEnumerable<Log> GetAll()
        {

            return _context.Logs.Include(c => c.Categories).AsEnumerable();


        }

我尝试将virtual关键字放在类别集合中(在Log类中),但无论我尝试什么,我都会从服务器返回null categories。< / p>

[{"id":0,"source":"seed","title":"seed","timestamp":"2018-03-19T13:21:27.0034628","categories":null}]

非常感谢任何帮助。

编辑:

根据反馈,我为Log创建了一个初始化ICollection的构造函数。

public Log()
{
    this.Categories = new List<Category>();
}

现在,而不是null我得到一个空列表 [{"id":0,"source":"seed","title":"seed","timestamp":"2018-03-19T13:21:27.0034628","categories":[]}]

朝着正确的方向迈出了一步,但还没有。

编辑:为了澄清,我使用的是EF-Core 2.0.2 编辑:另外,我使用的是.NET Core 2.05

“解决方案”:我将我的项目转换为使用带有完整.Net Framework的Asp.net,它似乎可行。我不知道为什么它拒绝使用带有.net核心的asp.net。

1 个答案:

答案 0 :(得分:0)

问题是您的一对多关系配置不正确。按如下方式编写模型类:

public class Log
{
    public Log()
    {
        this.Categories = new List<Category>();
    }

    public int ID { get; set; }
    public string Source { get; set; }
    public string Title { get; set; }
    public DateTime Timestamp { get; set; }
    public ICollection<Category> Categories { get; set; }


}

public class Category
{
    public int ID { get; set; }

    [ForeignKey("Log")]
    public int LogID { get; set;}
    public string Key { get; set; }
    public string Value { get; set; }

    public Log Log {get; set;}
}

希望,这将解决您的问题..