我有两个相关的模型。
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; }
}
,第二个是这样的
public class UserModels
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int user_id { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "User Name")]
[StringLength(20, ErrorMessage = "The {0} must be at least 3 characters long.", MinimumLength = 3)]
public string user_name { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
[StringLength(10, ErrorMessage = "The {0} must be at least 4 characters long.", MinimumLength = 4)]
public string user_pass { get; set; }
[DataType(DataType.EmailAddress)]
[Display(Name = "Email")]
[StringLength(50, ErrorMessage = "The {0} must be at least 6 characters long.", MinimumLength = 6)]
public string UserEmail { get; set; }
[Display(Name = "Registeration Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime RegDate { get; set; }
[Display(Name = "Enable User")]
public bool status { get; set; }
//[Bindable(false)]
public int RoleId { get; set; }
[Display(Name = "User Roles")]
public virtual RolesModels Roles { get; set; }
}
问题是,我希望能够使用以下列检索记录:
User Name | Email | Registration Date | Enable User | Role Caption
这是我的linq to sql code:
var model = from c in db.UserModels
join o in db.RolesModels on c.RoleId equals o.RoleId
where 1==1
select c;
答案 0 :(得分:1)
您不需要where 1=1
部分,因为它始终为真,不会影响结果集。您还拥有角色的导航属性,因此您无需手动加入实体:
from u in db.UserModels
select new {
UserName = user_name,
Email = UserEmail,
RegistrationDate = RegDate,
EnableUser = status,
RoleCaption = u.Roles.Caption
}
如果有可能用户无法分配角色,请考虑进行空检查。
答案 1 :(得分:0)
你的意思是这个
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();
答案 2 :(得分:0)
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();
做这样的事情。
答案 3 :(得分:0)
我能够使用Consoto大学的示例项目来解决这个问题。 这是解决方案:
var m = db.UserModels.Include(u => u.Roles);
return View(m.ToList());
和modelItem =&gt; item.Roles.Caption使用导航属性从Roles模型中获取角色标题。
感谢所有人的尝试。