简体   繁体   English

C#的实体框架,检索保存的对象

[英]entity framework with c#, retrieving saved objects

I'm new to EF, and after looking at tutorials, it seems like I can save the data just fine, but don't know the code to retrieve it. 我是EF的新手,看完教程后,似乎可以很好地保存数据,但不知道检索数据的代码。 My class looks like 我的课看起来像

public class Item
{
    [Key]
    public int index { get; set; }
    public string name;
    public List<string> type;
    public List<string> def;
    public HashSet<string> syns;
    public HashSet<string> generator_list = new HashSet<string>();
    public List<Point> related_items2 = new List<Point>();
}

And the EF code looks like EF代码看起来像

    using (var ctx = new Context())
    {
        foreach (Item block in items)
        {
            ctx.items_db.Add(block);
        }
        ctx.SaveChanges();

        var test = from b in ctx.items_db
                    orderby b.index
                    select b;
    }

I have 9000 Item instances, and I'd just like to save them in a database and then retrieve them into a List<Item> with all the instances. 我有9000个Item实例,我只想将它们保存在数据库中,然后将它们与所有实例一起检索到List<Item> But I don't think I'm doing it right with var test , because that doesn't appear to be a List<Item> and I can't seem to access it outside of the using statement block. 但是我不认为我在var test做得对,因为这似乎不是List<Item>而且我似乎无法在using语句块之外访问它。

The only reason I'm doing this is because the ONLY thing I want is to save the related_items2 property (so I don't have to regenerate it upon every restart) because there are 9000 elements in it and it takes a while (20 min) to generate 9000 instances. 我这样做的唯一原因是,我唯一想做的就是保存related_items2属性(因此,我不必在每次重新启动时都重新生成它),因为其中有9000个元素,并且要花一些时间(20分钟)生成9000个实例。 I tried using protobuff but that still takes up 200mb and I get errors when I try to read the data back in. 我尝试使用prob,但仍然占用200 mb,尝试重新读回数据时出现错误。

you must use .ToList() to change data to list of Items 您必须使用.ToList()将数据更改为项目列表
if you not using .ToList your test variable is IQueryable and not list of data that out side of using not worked 如果不使用.ToList您的测试变量是IQueryable ,而不是使用.ToList的数据列表不起作用

var test=new List<Item>();
using (var ctx = new Context())
{
    foreach (Item block in items)
    {
        ctx.items_db.Add(block);
    }
    ctx.SaveChanges();

    test = (from b in ctx.items_db
                orderby b.index
                select b).ToList();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM