EF4 code with the first addition of items that I don’t understand very well

I don’t understand why the code does not first add a new element to the collection until it calls savechanges. I installed EF4.1 from NuGet (4.1.10331.0). I created the following example:

public class TinyItem
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class TinyContext : DbContext
{
    public virtual DbSet<TinyItem> Items { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        using (var ctx1 = new TinyContext())
        {
            ListItems(ctx1, "Start");

            ctx1.Items.Add(new TinyItem { Name = "Test1" });
            ListItems(ctx1, "After add");

            ctx1.SaveChanges();
            ListItems(ctx1, "After commit");
        }

        Console.ReadKey();
    }

    public static void ListItems(TinyContext ctx, string label="")
    {
        Console.WriteLine("=========================================");
        Console.WriteLine(label);
        Console.WriteLine(string.Format("Items.Local: {0}", ctx.Items.Local.Count));
        foreach (var item in ctx.Items.Local)
        {
            Console.WriteLine(string.Format("{0} = {1}", item.Id, item.Name));
        }
        Console.WriteLine(string.Format("Items: {0}", ctx.Items.Count()));
        foreach (var item in ctx.Items)
        {
            Console.WriteLine(string.Format("{0} = {1}", item.Id, item.Name));
        }
        Console.WriteLine("=========================================");
    }

First I added one record to the database. Then I ran this and these are the results:

    =========================================
    Start
    Items.Local: 0
    Items: 1
    4 = Test1
    =========================================
    =========================================
    After add
    Items.Local: 2
    4 = Test1
    0 = Test1
    Items: 1
    4 = Test1
    =========================================
    =========================================
    After commit
    Items.Local: 2
    4 = Test1
    5 = Test1
    Items: 2
    4 = Test1
    5 = Test1
    =========================================

My questions: - Why does the first call to ctx.Items.Local give my zero? - Why does the list of ctx.Items elements not contain the element just added before I called SaveChanges?

+5
source share
1 answer

Why does the first call to ctx.Items.Local give my null elements?

EF - ( ). , - . 0.

msdn Local

ObservableCollection, , . . , .


ctx.Items , SaveChanges?

ctx.Items, . 1 ( SaveChanges()), .

+4

All Articles