更新实体框架5,一对一关系

本文关键字:一对一 关系 实体 框架 更新 | 更新日期: 2023-09-27 17:57:32

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();
        }
    }

我想创建新的Customer并使用数据库中的卡,当我保存到数据库时,Customer表中的card_Id是存在的,但card表中的Customer_Id是空的。如何更新表卡中的Customer_Id?

对不起,我的英语不好:(感谢您的帮助:(

更新实体框架5,一对一关系

您尝试过吗:

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();
}