Reputation: 172
public class Card : EntityBase
{
[Required]
[MaxLength(16)]
[RegularExpression("([0-9]+)", ErrorMessage = "Only number allowed")]
public string Number { get; set; }
public bool IsActive { get; set; }
public Customer Customer { get; set; }
}
public class Customer : EntityBase
{
public Customer()
{
Address = new Address();
}
[Required]
[MaxLength(50)]
public string Name { get; set; }
public string PhoneNumber { get; set; }
public Address Address { get; set; }
[ForeignKey("Card")]
public int Card_Id { get; set; }
public Card Card { get; set; }
}
public class CustomerConfiguration : EntityTypeConfiguration<Customer>
{
public CustomerConfiguration()
{
HasRequired(x => x.Card).WithMany().HasForeignKey(x => x.Card_Id);
}
}
static void CreateCustomer()
{
using (var context = new BenzineFleetContext())
{
var card = var card = new Card
{
Number = "123456"
};
context.Cards.Add(card);
context.SaveChanges();
}
using (var context = new BenzineFleetContext())
{
var card = context.Cards.First(c => c.Number == "123456");
var customer = new Customer { Name = "Rayz", Card = card };
context.Customers.Add(customer);
context.SaveChanges();
}
}
I want to create new Customer and use card from database, when i save to database, Card_Id in table Customer is exist, but Customer_Id in table Card is null. How to update Customer_Id in table card?
Sorry my english is bad :( Thanks for help :)
Upvotes: 0
Views: 1438
Reputation: 6786
Have you tried:
using (var context = new BenzineFleetContext())
{
var card = context.Cards.First(c => c.Number == "123456");
var customer = new Customer { Name = "Rayz", Card = card };
card.Customer = customer;
context.SaveChanges();
}
Upvotes: 1