简体   繁体   中英

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. 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

    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. 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.

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. I tried using protobuff but that still takes up 200mb and I get errors when I try to read the data back in.

you must use .ToList() to change data to list of Items
if you not using .ToList your test variable is IQueryable and not list of data that out side of using not worked

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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