Rog*_*Far 6 entity-framework ef-code-first entity-framework-5
我有2个简单的类:
public class Setting
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid SettingId { get; set; }
[Required]
public String Name { get; set; }
public String Value { get; set; }
[Required]
public SettingCategory SettingCategory { get; set; }
}
public class SettingCategory
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid SettingCategoryId { get; set; }
[Required]
public String Value { get; set; }
public ICollection<Setting> Settings { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
当我SettingCategory从数据库中检索a时,集合Settings始终为null.
当我做它virtual然后会说:The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
我怎样才能访问我的Settings列表?
另一种方式是工作,如果我Setting从数据库中检索SettingCategory属性已填充.
这是我最初的代码迁移脚本:
CreateTable(
"dbo.Settings",
c => new
{
SettingId = c.Guid(nullable: false, identity: true),
Name = c.String(nullable: false),
Value = c.String(),
SettingCategory_SettingCategoryId = c.Guid(nullable: false),
})
.PrimaryKey(t => t.SettingId)
.ForeignKey("dbo.SettingCategories", t => t.SettingCategory_SettingCategoryId, cascadeDelete: true)
.Index(t => t.SettingCategory_SettingCategoryId);
CreateTable(
"dbo.SettingCategories",
c => new
{
SettingCategoryId = c.Guid(nullable: false, identity: true),
Value = c.String(nullable: false),
})
.PrimaryKey(t => t.SettingCategoryId);
Run Code Online (Sandbox Code Playgroud)
这是从数据库中获取它的部分:
public SettingCategory Get(Guid settingCategoryId)
{
using (var context = new BackofficeContext())
{
return context
.SettingCategories
.FirstOrDefault(s => s.SettingCategoryId == settingCategoryId);
}
}
Run Code Online (Sandbox Code Playgroud)
回答
我忘记了包含.SettingCategories,但我正在尝试使用lambda:
public SettingCategory Get(Guid settingCategoryId)
{
using (var context = new BackofficeContext())
{
return context
.SettingCategories
.Include(s => s.Settings)
.FirstOrDefault(s => s.SettingCategoryId == settingCategoryId);
}
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,但这样做:
public SettingCategory Get(Guid settingCategoryId)
{
using (var context = new BackofficeContext())
{
return context
.SettingCategories
.Include("Settings")
.FirstOrDefault(s => s.SettingCategoryId == settingCategoryId);
}
}
Run Code Online (Sandbox Code Playgroud)
cad*_*ll0 16
因为你正在处理你,所以BackofficeContext你不能使用LazyLoading,这就是Settings虚拟时发生的事情.
您可以增加您的生命周期BackofficeContext或急切负载Settings.您可以使用急切加载Include.
public SettingCategory Get(Guid settingCategoryId)
{
using (var context = new BackofficeContext())
{
return context
.SettingCategories
.Include(s => s.Settings)
.FirstOrDefault(s => s.SettingCategoryId == settingCategoryId);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12878 次 |
| 最近记录: |