После добавления данных в CustomerId записывается NULL, почему?
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class Customer
{
public int CustomerId { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int Age { get; set; }
// Ссылка на заказы
public virtual List<Order> Orders { get; set; }
}
public class Order
{
public int OrderId { get; set; }
public string ProductName { get; set; }
public int Quantity { get; set; }
public DateTime PurchaseDate { get; set; }
// Ссылка на покупателя
public Customer Customer { get; set; }
}
public void Execute()
{
using (Technic context = new Technic())
{
context.Customers.Add(new Customer() { Name = this.name, Email = this.email, Age = this.age });
context.Orders.Add(new Order() { ProductName = this.productname, Quantity = this.quantity });
context.SaveChanges();
}
Console.WriteLine("Record is Created");
}
Скорее всего так происходит потому, что экземпляр Order никак не ссылается на экземпляр Customer, т.е. между ними нет никакой связи. Другими словами, Вам нужно эту связь создать. Не уверен, но попробуйте так:
using (Technic context = new Technic()) {
Customer customer = new Customer() {
Name = this.name,
Email = this.email,
Age = this.age
};
Order order = new Order() {
ProductName = this.productname,
Quantity = this.quantity,
Customer = customer
};
context.Customers.Add(customer);
context.Orders.Add(order);
context.SaveChanges();
}
Продвижение своими сайтами как стратегия роста и независимости