将数据库中的两个表与实体框架一起使用



我从实体框架开始,我想知道是否可以通过main name="DBEntities"方法访问每个表?

这是我的代码,如果我已经在使用数据库的基本方法,我不清楚为什么我没有得到表2中的数据。

App.config

<connectionStrings>
<add name="DBEntities" 
connectionString="metadata=res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=DESKTOP-GN4506J;initial catalog=Test;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" 
providerName="System.Data.EntityClient" />
</connectionStrings>

Form1.cs

public partial class FormMenu : Form
{
Table1 firstTable = new Table1 ();
Table2 secondTable = new Table2();
Table3 thirdTable = new Table3();
using (DBEntities db = new DBEntities())
{
try
{
firstTable = db.Table1.Where(x => x.BATCH_ID == cardUID).FirstOrDefault();
if (firstTable == null)
{
return;
}
else
{
thirdTable = db.Table3.Where(x => x.LPE_ID == firstTable.MA_ID).FirstOrDefault();
secondTable = db.Table2.Where(x => x.ZPZ_Datum.Value.Date == DateTime.Now.Date && x.ZPZ_LPE_ID == firstTable.MA_ID).LastOrDefault();
// here the application shoots me because in secondTable I don't get data based on db.Table2, where am I making a mistake?
if (thirdTable == null)
{
db.Entry(thirdTable ).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
}
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
};
}

错误消息:

"INQ to Entities"无法识别"ApplicationTest.Table2"LastOrDefault[Table2](System.Linq.IQUERABLE`1[ApplicationTest.Table2](方法,而此方法不能为翻译成记忆表达。

我可以不以这种方式访问两个表吗?那么,为什么要输入第一个db.Table1数据呢?有人能向我解释一下并给我一个解决方案吗。

似乎LastOrDefault无法转换为t-SQL,Linq to Entities无法识别它。您可以修改代码如下:

secondTable = db.Table2
.Where(x => x.ZPZ_Datum.Value.Date == DateTime.Now.Date 
&& x.ZPZ_LPE_ID == firstTable.MA_ID)
.OrderByDescending(c => c.SomeColumn)
.FirstOrDefault(); //Or Take(1)

作为另一种选择,您也可以在Where语句之后使用.ToList()AsEnumerable方法,就像这个答案一样https://stackoverflow.com/a/60896583/2946329,但您应该注意,通过在加载数据后使用它们,任何进一步的操作都是使用Linq-to-Objects对内存中已经存在的数据执行的。所以,如果你关心性能,我不确定在你的情况下使用这种方法是一个好的选择,我不能保证!

最新更新