我试图用两个列表来种子数据库。第一个列表只是一堆项目。第二个列表是一堆引用第一个列表的垃圾。我试图通过LINQ在第二个垃圾列表中引用第一个列表中的项目,但我相当肯定我做得不对:
例如,清单1:
var items = new List<Item>()
{
new Item { ItemtId = 1, DateTime = new DateTime(2014, 09, 05, 12, 30, 30), Text = "Cheese" },
new Item { ItemtId = 1, DateTime = new DateTime(2014, 09, 05, 12, 30, 30), Text = "Lettuce" },
new Item { ItemtId = 1, DateTime = new DateTime(2014, 09, 05, 12, 30, 30), Text = "Ground Beef" },
new Item { ItemtId = 1, DateTime = new DateTime(2014, 09, 03, 12, 30, 30), Text = "Ketchup" },
new Item { ItemtId = 1, DateTime = new DateTime(2014, 09, 03, 12, 30, 30), Text = "Mustard" },
};
var junk= new List<Junk>()
{
new Junk { JunkId = 1, DateTime = new DateTime(2014, 09, 05, 10, 00, 00), Items = items.Where(d => d.DateTime.ToShortDateString() == new DateTime(2014, 09, 05).ToShortDateString()},
new Junk { JunkId = 2, DateTime = new DateTime(2014, 09, 03, 11, 00, 00), Items = items.Where(d => d.DateTime.ToShortDateString() == new DateTime(2014, 09, 03).ToShortDateString()}
};
这似乎应该是我的答案,因为我只对日期而不是时间感兴趣,但它并不像这样种子。我收到错误:
LINQ to Entities无法识别方法&#39; System.String ToShortDateString()&#39;方法,这个方法无法翻译成 商店表达。
关于如何构建更好的解决方案的任何想法?
更新
看起来我没有准确地将我的代码转录到网站上,最终找到了我的问题。
在原始代码中,我有:
new Junk { JunkId = 1, DateTime = new DateTime(2014, 09, 05, 10, 00, 00), Items = context.Items.Where(d => d.DateTime.Date == new DateTime(2014, 09, 05) }
我什么时候应该
new Junk { JunkId = 1, DateTime = new DateTime(2014, 09, 05, 10, 00, 00), Items = items.Where(d => d.DateTime.Date == new DateTime(2014, 09, 05) }
我不必要地调用.ToShortDateString()
答案 0 :(得分:2)
将过滤器更改为:
.Where(d => d.DateTime.Date == new DateTime(2014, 09, 05))
答案 1 :(得分:1)
您可以使用TruncateTime
类的EntityFunctions
功能。
new Junk { JunkId = 1, DateTime = new DateTime(2014, 09, 05, 10, 00, 00), Items = items.Where(d => EntityFunctions.TruncateTime(d.DateTime) == EntityFunctions.TruncateTime(new DateTime(2014, 09, 05))}
注意:如果您使用的是EntityFramework 6,那么它应该是EntityFramework.dll中的System.Data.Entity.DbFunctions.TruncateTime(...)方法。
答案 2 :(得分:1)
你的子查询(Items =垃圾变量的一部分)不是列表,而是可枚举的,因此它不会被实现,直到它被枚举,并且它没有被列举直到您使用它,在您的linq中实体查询。
如果你改变它:
var junk= new List<Junk>()
{
new Junk { JunkId = 1, DateTime = new DateTime(2014, 09, 05, 10, 00, 00), Items = items.Where(d => d.DateTime.ToShortDateString() == new DateTime(2014, 09, 05).ToShortDateString()).ToList()}, // this one will work as it gets materialized right now, not later, so by the time you pass it to linq to entities later it will already be a simple list of diferences, it won't try to compute "toshortdatestring" later, that will already be done
new Junk { JunkId = 2, DateTime = new DateTime(2014, 09, 03, 11, 00, 00), Items = items.Where(d => d.DateTime.ToShortDateString() == new DateTime(2014, 09, 03).ToShortDateString()}
};