【问题标题】:find a field in a table via a value of another table field value using EF and Linq使用 EF 和 Linq 通过另一个表字段值的值在表中查找字段
【发布时间】:2015-08-17 23:28:46
【问题描述】:

我有两个这样的模型:

public class ServiceModel
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual string GroupName { get; set; }
    public virtual bool IsActive { get; set; }

}

和:

 public class ShopServiceModel
{
    public virtual int Id { get; set; }
    public virtual int ShopId { get; set; }
    public virtual int ServiceId { get; set; }
    public virtual int Time { get; set; }
    public virtual bool IsActive { get; set; }
    public virtual ServiceModel  Service { get; set; }
}

并且使用实体框架使我在数据库中创建了这些表:

服务表:

ShopService 表:

但是,我想使用 Linq 查询并从 ShopService 表中获取 ServiceId 字段值并在 Serivce 表中查找服务名称我的意思是 Service 表中的 Name 字段值,那么我该怎么做,我的模型是否正确执行此操作?

【问题讨论】:

  • 你是在问如何在 Linq 中加入吗?
  • 这就是您的导航属性 Service 的用途。 var myShopService = context.ShopServiceModel.Include(s => s.Service).FirstOrDefault(s => s.ServiceId == valueToFind);然后您可以使用“myShopService.Service.Name”获取名称

标签: c# mysql sql-server linq entity-framework


【解决方案1】:

您的模型是正确的。要获取 ShopService(和相应的服务名称),您只需执行以下操作:

var shopService=db.ShopServices
  .Include(s=>s.Service)
  .Where(ss=>ss.Id=1);

Console.WriteLine("Shop Service:{0} has a name of {1} and took {2} minutes",
  shopService.Id,shopService.Service.Name,ShopService.Time);

或全部列出:

var shopServices=db.ShopServices
  .Include(s=>s.Service);
foreach(var shopService in shopServices)
{    
  Console.WriteLine("Shop Service:{0} has a name of {1} and took {2} minutes",
    shopService.Id,shopService.Service.Name,ShopService.Time);
}

或者使用投影拉出你想要的字段:

var ss=db.ShopServices.Select(s=>new {Id=s.Id,Name=s.Service.Name,Time=s.Time});
foreach(var s in ss)
{    
  Console.WriteLine("Shop Service:{0} has a name of {1} and took {2} minutes",
    s.Id,s.Name,s.Time);
}

【讨论】:

    猜你喜欢
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 2015-10-02
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    • 2013-01-04
    相关资源
    最近更新 更多