Asp.net mvc 如何在实体框架中连接两个表
我的项目中有两张桌子。我想用便笺书写者的用户名获取便笺。如何在LINQ中加入此表 注:实体:Asp.net mvc 如何在实体框架中连接两个表,asp.net-mvc,database,entity-framework,linq,entity-framework-6,Asp.net Mvc,Database,Entity Framework,Linq,Entity Framework 6,我的项目中有两张桌子。我想用便笺书写者的用户名获取便笺。如何在LINQ中加入此表 注:实体: public class Note : MyEntitesBase { public string Tittle { get; set; } public string Text { get; set; } public bool IsDraft { get; set; } public bool IsApproved
public class Note : MyEntitesBase
{
public string Tittle { get; set; }
public string Text { get; set; }
public bool IsDraft { get; set; }
public bool IsApproved { get; set; }
public int CategoryID { get; set; }
public virtual EvernoteUser Owner { get; set; }
public virtual List<Comment> Comments { get; set; }
public virtual Category Category { get; set; }
public virtual List<Liked> Likes { get; set; }
public Note()
{
Comments = new List<Comment>();
Likes = new List<Liked>();
}
}
公共类注释:MyEntiteBase
{
公共字符串标题{get;set;}
公共字符串文本{get;set;}
公共bool IsDraft{get;set;}
公共布尔值已批准{get;set;}
public int CategoryID{get;set;}
公共虚拟用户所有者{get;set;}
公共虚拟列表注释{get;set;}
公共虚拟类别{get;set;}
公共虚拟列表类似于{get;set;}
公共说明()
{
注释=新列表();
Likes=新列表();
}
}
EvernoteUser实体:
public class EvernoteUser : MyEntitesBase
{
public string Name { get; set; }
public string Surname { get; set; }
public string Username { get; set; }
/*Exc */
public Guid ActivateGuid { get; set; }
public virtual List<Note> Notes { get; set; }
public virtual List<Comment> Comments { get; set; }
public virtual List<Liked> Likes { get; set; }
}
公共类EvernoteUser:MyEntiteBase
{
公共字符串名称{get;set;}
公共字符串姓氏{get;set;}
公共字符串用户名{get;set;}
/*Exc*/
公共Guid ActivateGuid{get;set;}
公共虚拟列表注释{get;set;}
公共虚拟列表注释{get;set;}
公共虚拟列表类似于{get;set;}
}
在对Notes进行查询时,需要立即加载Owner表数据,以便在访问.Owner属性时不为null。例如:
Note noteWithOwner = _context.Notes
.Include(x => x.Owner) // Eager load the Owner table data into the object graph.
.SingleOrDefault(x => x.ID == noteID);
看起来您要求的是:note.Owner.Username-其中note是note实体有时(并非总是)当我使用note.Owner.Username访问Username参数时出现“对象引用未设置为对象实例”错误。然后在创建过程中没有设置所有者-您需要对此进行保护。i、 e.所有者不是creationShow控制器代码的强制约束。我将其作为以下视图发送。第一次创建视图时没有错误,但经过一定时间后会收到错误。我认为实体框架是dispose of dbContext。您有不同的查询来访问数据吗?它们在链中都有.Include(…)方法吗?您是否直接通过SQL检查数据库数据以检查所有者。用户名不为空?我通过数据库检查,没有所有者的注释。