c# - 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 来做到这一点吗?
解决方案
如果您要求避免使用 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”变量都会有一个相应的“成员”列表。
推荐阅读
- android - Android Studio:通过 FileProvider 共享文件错误 E/FilePathConverter resolveFilePath Couldn't read row 0, col -1 from CursorWindow
- java - 怎么能很快写在changeValue函数下面?
- macos - Qemu:在 MacOS X 上使用 Buster OS 模拟 Raspberry pi(CLI 有效,但屏幕空白)
- dagger-2 - 匕首子组件构建器可以设置数据(模块除外)吗?
- c++ - 对 aruco 函数的未定义引用
- python - OpenCV - 轮廓未检测到 jpg 中的正方形
- python - 如何在字符串格式中对十六进制进行对齐
- flutter - 将数据从一个小部件传递到另一个小部件
- java - 为什么尝试在 Java 中拆分字符串时出现空字符串?以及如何解决?
- mongodb - $multiply 在 $project 字段中提供 null