如何使1:模型之间的许多关系具有不同的查询(linq语法)
本文关键字:查询 语法 linq 关系 何使 模型 之间 许多 | 更新日期: 2023-09-27 18:14:35
我有这个:
模型:
{
[Table("Requests")]
public partial class RequestsModel
{
public RequestsModel()
{
this.CountView = new HashSet<RequestCountViewModels>();
}
[Key]
public int Id { get; set; }
public int? Sender { get; set; }
public int? Type { get; set; }
public string Subject { get; set; }
public string Text { get; set; }
public int? Adtype { get; set; }
public int? Status { get; set; }
[Column(TypeName = "date")]
public DateTime? SDate { get; set; }
[Column(TypeName = "date")]
public DateTime? EDate { get; set; }
public DateTime? RDate { get; set; }
public DateTime? PayDate { get; set; }
public DateTime? RespDate { get; set; }
public long? Counter { get; set; }
public string Tags { get; set; }
public string Maps { get; set; }
public int? AccBy { get; set; }
public virtual ICollection<RequestCountViewModels> CountView { get; set; }
}
[Table("Counter")]
public partial class RequestCountViewModels
{
[Key]
public long Id { get; set; }
[ForeignKey("ParentMdl")]
public int? ReqId { get; set; }
public string IP { get; set; }
public virtual RequestsModel ParentMdl { get; set; }
public DateTime? Time { get; set; }
}
}
HomeController:
public virtual ActionResult Advs(string id)
{
var model = _requestService.GetAdvertise(Convert.ToInt32(id));
return View(model);
}
RequestsService.cs
public RequestsModel GetAdvertise(int AdID)
{
return
_ctx.Requests
.AsNoTracking()
.FirstOrDefault(a => a.Id == AdID && a.Type == 1);
}
RequestsConfig.cs
HasMany(a => a.CountView)
.WithRequired(a => a.ParentMdl)
.HasForeignKey(a => a.ReqId);
这些是我的代码,现在我想使RequestsModel和RequestCountViewModel之间的关系,以便从remove db检索相关的表数据它将获得请求表,但需要为每一行检索viewcount表并填充到ICOLLECTION中帮帮我!英语不好
好的,你需要做一些像这样的东西:
public GetData()
{
var data = _ctx.Requests
.Include(p => p.CountView)
.AsNoTracking()
.Select(a => a.CountView)
.ToList();
return data;
}
我找到了解决我自己问题的办法RequestCountViewModels应该像这样:
[Table("Counter")]
public partial class RequestCountViewModels
{
public long Id { get; set; }
public string IP { get; set; }
[ForeignKey("ReqId")]
public virtual RequestsModel ParentMdl { get; set; }
public int ReqId { get; set; }
public DateTime Time { get; set; }
}
RequestService.cs :
public virtual RequestsModel GetAdvertises(int AdID)
{
return _requests
.AsNoTracking()
.Include(v => v.ViewCounts)
.Cacheable()
.FirstOrDefault(a => a.Id == AdID && a.Type == 1);
}
,考虑到for loop
语句应该代替foreach