【问题标题】:How to update parent and child table in one transaction in Entity framework如何在实体框架中的一个事务中更新父子表
【发布时间】:2014-01-23 08:39:26
【问题描述】:

假设,我有以下父表结构,

public partial class CustomerDetail
    {
        public CustomerDetail()
        {
            this.DependentDetails = new HashSet<DependentDetail>();

        }

        public int CustomerId { get; set; }
        public string Title { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }


        public virtual ICollection<DependentDetail> DependentDetails { get; set; }

    }

而子表结构是,

 public partial class DependentDetail
    {
        public int DependentId { get; set; }
        public Nullable<int> CustomerId { get; set; }
        public string Relationship { get; set; }
        public string Gender { get; set; }
        public Nullable<System.DateTime> DateOfBirth { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public virtual CustomerDetail CustomerDetail { get; set; }
    }

如果我想使用实体框架更新两个表,该怎么做?

请提出建议。

【问题讨论】:

    标签: entity-framework c#-4.0 entity-framework-4 linq-to-entities


    【解决方案1】:

    在使用实体框架向数据库插入新记录时

    var customer=new CustomerDetail();
    customer.Title ="Customer";
    customer.FirstName ="First";
    customer.LastName ="Last";
    customer.Gender ="Male";
    var dependent=new DependentDetail();
    dependent.Relationship ="Test";
    .
    .
    .
    customer.DependentDetails.Add(dependent);
    
    while updating dependent
    
    var customer=Repository.find(CustomerId);
    //update customer details here
    var dependent=customer.DependentDetails.where(x=>x.DependentId ==DependentId).FirstOrDefault();
    dependent.RelationShip="Test";
    
    ///call save function
    

    【讨论】:

    • 我想一次性更新 Customer 和 Dependent 表。
    • 在设置依赖数据后调用 Repository.save() 以便更新客户和依赖项
    猜你喜欢
    • 1970-01-01
    • 2020-12-10
    • 2014-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多