首页 > 解决方案 > C# lambda 加入和更新

问题描述

我使用实体框架。类列表是

class List
{
public string cid { get; set; }
public string type{ get; set; }
public string memo{ get; set; }
public DateTime sdate{ get; set; }
}

并数约50。

我想加入关于成员的表格。成员的列是:id,cid,name,address

var result =
thelist.Where(w => !string.IsNullOrWhiteSpace(type)).Join(db.members,list => list.cid,member => member,(list,member) => list).ToList();

-> 不确定是否有效。

我想获取表成员中 cid 的列表记录。并用成员的名字更新列表的备忘录。

我可以通过使用 lambda 来做到这一点吗?

标签: c#linqjoinlambda

解决方案


如果您要求避免使用 SQL,当然可以。但是您需要以特定方式设置表关系。

您应该在类中定义您的键和外键:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class Parent
{
    [Key]
    public string cid { get; set; }
    public string type{ get; set; }
    public string memo{ get; set; }
    public DateTime sdate{ get; set; }

    public virtual ICollection<Members> {get;set;}
}

public class Members{
    public virtual Parent Parent {get;set;}
    [Key]
    public int id {get;set;}
    [ForeignKey("Parent")] //This should match database table name
    public string cid {get;set;}
    //...other data types
}

您应该根据变量名称、可空性(如果数据库中有可空变量,请确保它在类中可空:int -> int?)准确地镜像数据库,外键应该匹配。

一旦您以一种简洁的方式设置了所有内容,将子表值连接到父表就很简单了:

//...

List<Parent> resultsWithChildren = _dbContext.Parent.Where(x => x.cid == "someid").Include(x => x.Members).ToList();

通过添加“包含”,EntityFramework 将加载它可以自动找到链接的所有表,这就是关系设置很重要的原因。

然后,您可以随心所欲地简单地遍历数据。每个“resultWithChildren”变量都会有一个相应的“成员”列表。


推荐阅读