【发布时间】:2018-03-19 17:47:19
【问题描述】:
我正在尝试与以下对象创建一对多关系。
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。
[{"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 框架的 Asp.net,它似乎可以工作。我不知道为什么它拒绝与带有 .net 核心的 asp.net 一起工作。
【问题讨论】:
-
也许不是您的问题,但是您将日志条目的 ID 设置为
[DatabaseGenerated(DatabaseGeneratedOption.None)],然后当您插入日志时,您没有将 ID 设置为任何值。如果您插入 1 个项目,这可以正常工作,但如果您插入多个项目,则会出现重复键错误 -
尝试在构造函数内的 Log 类中初始化您的类别 ICollection List。我不认为它已初始化。
-
@MohamoudMohamed 谢谢,我为它实现了一个初始化列表的构造函数。它不再返回
null,但它返回的列表是空的。 -
您需要单独创建类别对象,然后将其添加到 Log.Categories.Add("newCategory")。
-
@MohamoudMohamed 刚刚尝试创建类别对象,然后将它们添加到日志对象(在日志初始创建之后)。不幸的是,
categories仍然返回一个空列表
标签: c# asp.net entity-framework rest