我一直试图遵循一些基本的.Net核心教程,我想创建一个使用EF的Asp.net create。
基本上,.Include()似乎什么也不做,而且我甚至不认为这最初是一个必要的调用,老实说。
我有一个API,其中包含有想法的Goldfish,JSON正在为单独的对象很好地返回,除了我的导航属性在金鱼上总是为NULL:
[
{
"id": 1,
"name": "Bob",
"isAlive": true,
"food": 50,
"ideas": null
},..下面是Goldfish类(它也不适用于ICollection )
public class Goldfish
{
public long ID { get; set; }
public string Name { get; set; }
public bool IsAlive { get; set; }
public long Food { get; set; }
public IEnumerable<Idea> Ideas { get; set; }
}下面是Idea类(出于绝望,我使用了foreignkey属性来使其工作,以前我有一个GoldfishID属性。)
public class Idea
{
public long ID { get; set; }
public string Title { get; set; }
public string Gist { get; set; }
public long GoldfishID { get; set; }
[ForeignKey("GoldfishID")]
public Goldfish Goldfish { get; set; }
}我认为我的数据库是可以的,因为外键已经设置在我的Idea表上:
ALTER TABLE [dbo].[Ideas] WITH CHECK ADD CONSTRAINT
[FK_Ideas_Goldfish_GoldfishID] FOREIGN KEY([GoldfishID])
REFERENCES [dbo].[Goldfish] ([ID])
ON DELETE CASCADE
GO但是当我访问我的控制器方法时:
[HttpGet]
public IEnumerable<Goldfish> GetAll()
{
var stuff = _context.Goldfish.Include(i => i.Ideas);
return stuff.ToList();
// return _context.Goldfish.ToList();
}感谢全世界我最喜欢的工具,我知道运行的SQL没有连接,也没有任何想法--我的金鱼已经脑死亡了。
SELECT [g].[ID], [g].[Food], [g].[IsAlive], [g].[Name]
FROM [Goldfish] AS [g]请让我知道我要去哪里,wrong...is我的返回类型,不包括我想要的结构类型?我要说的是,我还没有在OnModelCreating中显式地设置所需的一对多,因为本教程没有这样做,以下是我的整个上下文:
public class GoldfishContext : DbContext
{
public GoldfishContext(DbContextOptions<GoldfishContext> options)
: base(options)
{
}
public DbSet<Goldfish> Goldfish { get; set; }
public DbSet<Idea> Ideas { get; set; }
//Interrupt the standard configuration of table names, the tutorial has this and it's nice to keep ffr
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Goldfish>().ToTable("Goldfish");
}
}我应该提一提!我在我的DBInitialise中添加了这些想法,它们肯定存在于db中:
var pondideas = new Idea[]
{
new Idea {Title="Bobs idea", Gist = "Give bob food", GoldfishID=1},
new Idea {Title="Bobs second idea", Gist = "Give bob more food", GoldfishID=1},
new Idea {Title="Nice idea", Gist = "Feed everyone", GoldfishID=1},
new Idea {Title="terrible idea", Gist = "Feed nobody", GoldfishID=1}
};发布于 2018-05-12 17:17:03
我已经指出了正确的方向(谢谢夏珠),我要明确地提出解决办法:
.Include()的正确包是Microsoft.EntityFrameworkCore
为此您需要添加:使用Microsoft.EntityFrameworkCore;
代码将使用错误的版本(.Net框架)运行,但是包含不会起任何作用。
一旦您添加了正确的库,并且如果您的模型像我的一样链接,您的API将超时,除非您将以下JsonOptions添加到启动中以防止循环引用混乱:
services.AddMvc()
.AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);https://stackoverflow.com/questions/50308418
复制相似问题