C# 实体框架实体列表始终为空
我有以下两种型号:C# 实体框架实体列表始终为空,c#,entity-framework,C#,Entity Framework,我有以下两种型号: public class Note { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public string Id { get; private set; } [Required] public string Creator { get; set; } public NoteProfile Profile { get; set; } [Required(
public class Note
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Id { get; private set; }
[Required] public string Creator { get; set; }
public NoteProfile Profile { get; set; }
[Required(AllowEmptyStrings = true)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Content { get; set; }
public static Note Create()
{
return new Note();
}
public Note GenerateId()
{
this.Id = Guid.NewGuid().ToString();
return this;
}
public Note Finalize()
{
this.GenerateId();
this.Profile = NoteProfile.Create().Finalize();
return this;
}
}
以及:
通过调试器检查user1
和user2
,发现在第一个上下文被处理之前创建的user1
,是一个带有0项的初始化列表,而在新上下文中创建的user2
为空
我的背景很简单:
public class Context : DbContext
{
public Context(string connectionString) : this(new MySqlConnection(connectionString), false)
{
}
public Context(DbConnection existing, bool contextOwnsConfig) : base(existing, contextOwnsConfig)
{
}
public DbSet<Note> Notes { get; set; }
public DbSet<User> Users { get; set; }
}
公共类上下文:DbContext
{
公共上下文(string connectionString):此(新的MySqlConnection(connectionString),false)
{
}
公共上下文(DbConnection existing,bool contextOwnsConfig):基本(existing,contextOwnsConfig)
{
}
公共DbSet注释{get;set;}
公共数据库集用户{get;set;}
}
数据库提供程序是MySQL。检查MySQL Workbench中EF生成的表可以发现外键确实存在:
添加Note
的新实例及其Creator
属性集等于我的用户的Id
会产生完全相同的结果
为什么会发生这种情况?您是否已配置
如果没有,您需要明确地包含一个相关实体,如下()
您的第一个示例之所以有效,是因为这些实体已经在上下文中
using (var context = new Context())
{
user2 = context
.Users
.Include(b => b.Notes)
.First(user => user.Id == entity.Id)
.Notes;
}
不要使用公共列表注释{get;set;}
而使用公共虚拟ICollection注释{get;set;}
public class Context : DbContext
{
public Context(string connectionString) : this(new MySqlConnection(connectionString), false)
{
}
public Context(DbConnection existing, bool contextOwnsConfig) : base(existing, contextOwnsConfig)
{
}
public DbSet<Note> Notes { get; set; }
public DbSet<User> Users { get; set; }
}
using (var context = new Context())
{
user2 = context
.Users
.Include(b => b.Notes)
.First(user => user.Id == entity.Id)
.Notes;
}