मुझे समझ में नहीं आता कि कोड पहले सहेजने के बाद संग्रह में नया आइटम क्यों नहीं जोड़ता है। मैंने NuGet (4.1.10331.0) से EF4.1 स्थापित किया। मैंने निम्नलिखित उदाहरण बनाया:ईएफ 4 कोड पहले आइटम को जोड़ने के लिए मुझे बहुत स्पष्ट नहीं है
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("=========================================");
}
सबसे पहले मैंने डेटाबेस में एक रिकॉर्ड जोड़ा। तब मैं इस भाग गया और इन परिणामों हैं:
=========================================
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
=========================================
मेरे प्रश्न हैं: - क्यों ctx.Items.Local करने के लिए पहली कॉल मेरी शून्य आइटम देता है? - ctx.Items की सूची में SaveChanges कहने से पहले केवल जोड़ा गया आइटम क्यों नहीं है?
अंतिम प्रश्न के बारे में: यह SaveChanges से पहले संग्रह के बारे में है, वहां आइटम जोड़ा नहीं गया है ("जोड़ने के बाद" अनुभाग)। –
@ जॉन ने उत्तर दिया – Eranga
ठीक है, लेकिन संग्रह वर्तमान सत्र/लेनदेन का प्रतिनिधित्व क्यों नहीं करता है? यह अब वर्तमान डेटाबेस का प्रतिनिधित्व करता है और मुझे इसकी परवाह नहीं है। –