c# - 如何从实体框架数据库中获取包含在类中的项目列表
问题描述
我的申请有问题。我无法从数据库中获取其中包含列表的对象。我真的不擅长实体框架,如果这是一个很大的错误,我很抱歉。
public List<Recipe> GetRecipes(Cook cook)
{
List<Recipe> L_Recipes = new List<Recipe>();
Cook Cook = dbc.DbCook.SingleOrDefault(c => c.Nickname == cook.Nickname);
L_Recipes = Cook.ListRecipes;
return L_Recipes;
}
这是Recipe
课程:
public class Recipe
{
//Attributes
public int Id { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public float CostPrice { get; set; }
public float SellingPrice { get; set; }
public DateTime Date { get; set; }
public List<Ingredient> ListIngredients { get; set; }
public List<Comment> ListComments { get; set; }
public Schedule Schedules { get; set; }
//Builder
public Recipe(string name, string type)
{
Name = name;
Type = type;
Date = DateTime.Now;
ListIngredients = new List<Ingredient>();
Schedules = new Schedule();
}
public Recipe(string name,string type,float costPrice,float SellingPrice,DateTime Date,List<Ingredient> ListIngredients,List<Comment> ListComments,Schedule Schedules)
{
this.Name = name;
this.Type = type;
this.CostPrice = costPrice;
this.SellingPrice = SellingPrice;
this.Date = Date;
this.ListIngredients = ListIngredients;
this.ListComments = ListComments;
this.Schedules = Schedules;
}
public Recipe() { ListIngredients = new List<Ingredient>(); }
//Methods
public void AddIngredient(Ingredient i)
{
ListIngredients.Add(i);
}
public float CalculCostPrice()
{
float cost = 0;
foreach (Ingredient ing in ListIngredients)
{
cost += ing.CalculCostIngredient();
}
return cost;
}
public float CalculSellingPrice()
{
return (float)(CalculCostPrice()*1.05);
}
public override string ToString()
{
string SP = string.Format("{0:00.00}", SellingPrice);
return $"{Name} for {SP} euros added the {Date.ToString()}";
}
}
问题是我收到了食谱的信息,但没有收到其中的清单。
它在 ASP.NET 中
包括代码:
public List<Recipe> GetRecipes(Cook cook)
{
List<Recipe> L_Recipes = new List<Recipe>();
Cook Cook = dbc.DbCook.Include(c => c.ListRecipes).singleOrDefault(c => c.Nickname == cook.Nickname);
L_Recipes = Cook.ListRecipes;
return L_Recipes;
}
解决方案
感谢https://stackoverflow.com/users/395675/philip-smith和https://stackoverflow.com/users/5748194/felipe-deveza
所以答案是使用 Include 并添加 using include:public List<Recipe> GetRecipes(Cook cook)
{
List<Recipe> L_Recipes = new List<Recipe>();
Cook Cook = dbc.DbCook.Include(c => c.ListRecipes).singleOrDefault(c => c.Nickname == cook.Nickname);
L_Recipes = Cook.ListRecipes;
return L_Recipes;
}
和 using:using System.Data.Entity;
推荐阅读
- ios - 如何使用 Swift 对数组进行 L2 标准化
- php - 尝试在 PHP 准备语句中添加变量时出错
- javascript - 将 object.keys 从对象数组映射到字符串
- python - Selenium Python - 无法单击 iframe 中的复选框,该 iframe 绑定到标签,并在隐藏元素中更新了值
- html - 如何使 AFTER li 背景元素可点击?
- gradle - Gradle 获取从哪个存储库解析依赖项(智能胖罐)
- c# - 存储对象时 C# 多播 UDP 数据包丢弃
- java - 向 jTree 添加多个子节点
- nsis - 使用 NSIS 在安全模式下卸载时如何停止卸载并弹出消息框?
- dialogflow-es - 在 Dialogflow 中替换参数值