C# Linq到sql返回相关数据
我有两个相关的模型C# Linq到sql返回相关数据,c#,asp.net-mvc,linq,C#,Asp.net Mvc,Linq,我有两个相关的模型 public class RolesModels { public RolesModels() { this.Users = new HashSet<UserModels>(); } [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int RoleId { get; set; } [Re
public class RolesModels
{
public RolesModels()
{
this.Users = new HashSet<UserModels>();
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int RoleId { get; set; }
[Required]
[DataType(DataType.Text)]
[StringLength(20, ErrorMessage = "The {0} must be at least 6 characters long.", MinimumLength = 6)]
[Display(Name = "Caption")]
public string Caption { get; set; }
[Display(Name = "Can Create")]
public bool createRole { get; set; }
[Display(Name = "Can View")]
public bool viewRole { get; set; }
[Display(Name = "Can Modify")]
public bool modifyRole { get; set; }
[Display(Name = "Can Delete")]
public bool deleteRole { get; set; }
public virtual ICollection<UserModels> Users { get; set; }
}
问题是,我希望能够检索具有以下列的记录:
User Name | Email | Registration Date | Enable User | Role Caption
以下是我的linq到sql代码:
var model = from c in db.UserModels
join o in db.RolesModels on c.RoleId equals o.RoleId
where 1==1
select c;
你是说像这样
var model = from c in db.UserModels
join o in db.RolesModels on c.RoleId equals o.RoleId
where 1==1
select new { c.user_name, c.UserEmail, c.RegDate, o.Caption, c.status}).ToList();
您不需要
where 1=1
part,因为它总是为您提供true,并且不会影响结果集。此外,您已经具有角色的导航属性,因此不需要手动加入实体:
from u in db.UserModels
select new {
UserName = user_name,
Email = UserEmail,
RegistrationDate = RegDate,
EnableUser = status,
RoleCaption = u.Roles.Caption
}
如果可能无法为用户分配角色,请考虑执行空检查
var model = (from c in db.UserModels.AsEnumerable()
join o in db.RolesModels.AsEnumerable() on c.RoleId equals o.RoleId
select new { c.user_name, c.UserEmail, c.RegDate, o.Caption, c.status}).ToList();
像这样做 我可以使用Consoto大学的样本项目来解决这个问题。 以下是解决方案:
var m = db.UserModels.Include(u => u.Roles);
return View(m.ToList());
和modeleItem=>item.Roles.Caption使用导航属性从角色模型中获取角色标题
谢谢大家的尝试。你错过了一个比较吗?@Silvermind不,我认为比较这个问题没有意义。编辑:对不起,你没有完成你的答案,我没有正确阅读;)它在u角色中的from r行中生成以下语法错误。源类型为“System.Data.Entity.DbSet”的查询表达式的后续from子句中不允许使用类型为“ApplicationName.Models.RolesModels”的表达式。调用'SelectMany'@Wale抱歉,Roles属性名称误导了类型推断(虽然它包含角色集合,但实际上它只包含一个角色),更新了代码现在我使用上面的方法得到一个错误。基于字典类型的错误。在我看来,我使用了IEnumerable。如何更正此错误?如果不列出它,将产生字符串错误。传递的是字符串而不是模型。
var m = db.UserModels.Include(u => u.Roles);
return View(m.ToList());