我建立了一个名为Project的类:
[表( 项目)] public class ProjectProfile { [Key] public int ID {获得; set ; } public string 名称{ get ; set ; } public string 描述{ get ; set ; } public virtual ICollection< User> HeadOf { get ; set ; } public virtual ICollection< User>工程师{获取; set ; } }写作不是问题,我构建了obejct,添加了HeadOf和Engineer集合并将其写入数据库。但是当我在课堂上阅读整篇文章时:
public class TodoToolContext:DbContext { // 任务: public DbSet< TaskProfile> TaskProfiles { get ; set ; } // 项目: public DbSet< ProjectProfile> ProjectProfiles { get ; set ; } }和电话: TodoToolContext db = new TodoToolContext(); List< ProjectProfile> list = db.ProjectProfiles.toList();
我得到一个项目列表(这是右),其中的所有本机数据类型都填充了数据(ID,名称,描述),这也是正确的,但ICollections是空的,因此项目与工程师和headofs之间的连接将丢失。 我现在的问题是,如何从数据库中读取这样的复杂对象?是否有必要回读每个项目,通过LINQ自己搜索正确的工程师和HeadOfs并再次自己建立连接? 难道有更简单的方法吗? 最好 J
解决方案要这样做你应该使用LINQ,你不能直接分配
I built up a class called Project:
[Table("Projects")] public class ProjectProfile { [Key] public int ID { get; set; } public string Name { get; set; } public string Description { get; set; } public virtual ICollection<User> HeadOf { get; set; } public virtual ICollection<User> Engineer{ get; set; } }Writing is not a problem, I built the obejct, add a HeadOf and Engineer collection and write it into the database. But when I read the whole thing by the class:
public class TodoToolContext : DbContext { // Tasks: public DbSet<TaskProfile> TaskProfiles { get; set; } // Projects: public DbSet<ProjectProfile> ProjectProfiles { get; set; } }and the call:
TodoToolContext db = new TodoToolContext(); List<ProjectProfile>list = db.ProjectProfiles.toList();I get a list of projects (which is right), all the native datatypes in it are filled with data (ID, Name, Description) which is also right, but the ICollections are empty, so the connection between the project and the engineers and headofs is lost. My question is now, how to read such "complex" objects from the database? Is it necessary to read back each "Project", search for the right "Engineers" and "HeadOfs" by myself via LINQ and make the connection by myself again? Isn`t there an easier way? Best J
解决方案 Hi , to do so you should use LINQ, you can not assign this directly更多推荐
EF代码中的复杂对象第一种方法
发布评论