Good day.
I create a database on the principle of Code-first. I have the following classes:
public class Product { public int Id { get; set; } public string Name { get; set; } public int? OrderId { get; set; } public Order Order { get; set; } } public class Order { public int Id { get; set; } public string Customer { get; set; } public ICollection<Product> Product { get; set; } public Order() { Product = new List<Product>(); } } class UserContext : DbContext { public UserContext() : base("DbConnection"){ } public virtual DbSet<Order> Orders { get; set; } public virtual DbSet<Product> Products { get; set; } } I create objects, write to the database.
By the way - the base - (localdb) \ v11.0 in the file .mdf (roughly speaking the first time I work with EF).
static void Main(string[] args) { using (UserContext db = new UserContext()) { // AddToDataBase(db); // получаем объекты из бд и выводим на консоль Console.Clear(); var orders = db.Orders.ToList(); foreach (var order in orders) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("{0}.{1}", order.Id, order.Customer); if (order.Product.Count > 1) { Console.ForegroundColor = ConsoleColor.Yellow; foreach (var pr in dp.Product) { Console.WriteLine("{0}.{1}", pr.Id, pr.Name); } } } } Console.Read(); } private static void AddToDataBase(UserContext db) { var pr1 = new Product() { Name = "phone" }; var pr2 = new Product() { Name = "car" }; db.Products.Add(pr1); db.Products.Add(pr2); db.SaveChanges(); var ord1 = new Order() { Customer = "Denis", Product = new Collection<Product>() { pr1 } }; var ord2 = new Order() { Customer = "test", Product = new Collection<Product>() { pr2 } }; Console.WriteLine("Объекты созданы."); db.Orders.Add(ord1); db.Orders.Add(ord2); db.SaveChanges(); Console.WriteLine("Объекты успешно сохранены"); } I do work by example.
After the first run, I execute the AddToDataBase method. During the second run, I just want to display the data read from the database. But in the end, it deduces that each Order is within the collection of Product 0 items.
Tell me, please, where to look and how to solve?
Thought to change the structure, but will it be correct?