简体   繁体   English

实体框架6更新表并插入到外键相关表中

[英]Entity Framework 6 update a table and insert into foreign key related tables

Not quiet sure how to word the title for this one so feel free to edit if it isn't accurate. 不安静确定如何为这个标题写标题,如果不准确,可以随意编辑。

Using an example, what I am trying to accomplish is update a record in table foo, and then create new records in a subsequent table that has the foo tables PK as foreign key, think One-to-Many relationship. 举一个例子,我想要完成的是更新表foo中的记录,然后在后续表中创建新记录,其中foo表PK为外键,请考虑一对多关系。

How do I update a table that has foreign key constraints and create a new related record(s) in these subsequent table(s)? 如何更新具有外键约束的表并在这些后续表中创建新的相关记录?

Currently I am using Entity Framework 6 to .Add and .Attach entities to the context and save them to the database. 目前我正在使用Entity Framework 6到.Add和.Attach实体到上下文并将它们保存到数据库中。

Edit 编辑

To clarify further what I am trying to achieve, the below object is a cut down made up example what I am trying to save to the context. 为了进一步澄清我想要实现的目标,下面的对象是一个减少的例子,我试图保存到上下文中。 If I try to .Add intObj after "Billy Bob" has already been created because he has bought a new car, another service, or his tyres have changed it will create a new Billy Bob record (duplicate) and the corresponding related tables. 如果我试图在“Billy Bob”创建之后添加intObj,因为他已经购买了一辆新车,另一项服务,或者他的轮胎已经改变,它将创建一个新的Billy Bob记录(重复)和相应的相关表。

        intObj.FirstName = "Billy";
        intObj.Lastname = "Bob";
        intObj.Important = 100;
        intObj.LastSeen = DateTime.Now.Date;
        intObj.Cars = new List<Car>{
            new Car{
                Model = "Commodore",
                Make = "Holden",
                YearMade = DateTime.Today.Date,
                Odometer = 15000,
                EmailWordCount = 500,
                TyreStatuss = new List<TyreStatus>{
                    new TyreStatus{
                        Tyre1 = "Good",
                        Tyre2 = "Good",
                        Tyre3 = "Okay",
                        Tyre4 = "Okay"
                        }                                 
                },
                Services = new List<Service>{
                    new Service{
                        Cost = "$500",
                        Time = "2 Days",
                        Date = DateTime.Today
                    }
                },
            }
        };

Thanks 谢谢

In the following snippets you have Employee class, which references two more entities: a collection of Assignment and a single Country. 在下面的代码片段中,您有Employee类,它引用了另外两个实体:Assignment和一个Country的集合。
ORMs like EF , NHibernate, etc... have a feature known as Transitive Persistence, that is, if an object (Assignment and Country) is referenced by a persistent one (Employee), then Assignments and Country will eventually become persistent too when, in your EF case, SaveChanges method gets invoked in the Context, without you explicitly save them. 像EF,NHibernate等ORM有一个称为传递持久性的特性,也就是说,如果一个对象(赋值和国家)被一个持久的(Employee)引用,那么赋值和国家最终也将成为持久性的,在EF的情况下,SaveChanges方法在Context中被调用,而不是你明确地保存它们。

    public class Employee
        {
            public virtual Guid Id { get; protected set; }
            public virtual string EmployeeNumber { get; set; }
            public virtual Country BirthCountry { get; set; }
            private ICollection<Assignment> _assignment = new List<Assignment>();
            public virtual ICollection<Assignment> Assignments
            {
                get
                {
                    return _assignment;
                }

                set
                {
                    _assignment= value;
                }
            }
        }

        public class Assignment
        {
            public virtual Guid Id { get; protected set; }
            public virtual DateTime BeginTime { get; set; }
            public virtual DateTime EndTime { get; set; }
            public virtual string Description{ get; set; } 
        }

        public class Country
        {
            public virtual Guid Id { get; protected set; }
            public virtual string Name { get; set; }
        }

   //Somewhere in your program      
   private void SaveAllChanges()
         {
             _db = new EFContext();
             //Creating a new employee here, but it can be one loaded from db
             var emp = new Employee { FirstName = "Emp Name", 
                 LastName = "Emp Last", EmployeeNumber = "XO1500"
             };
             emp.BirthCountry = new Country { Name = "Country1" };
             emp.Assignment.Add(new Assignment{ BeginTime = DateTime.Now,EndTime=DateTime.Now.AddHours(1) });

            //Only employee is explicitly added to the context
            _db.Employees.Add(emp); 
            //All the objects in the employee graph will be saved (inserted in this case) in the db. 
            _db.SaveChanges();
        }
    }

EDIT: 编辑:

That is very similar to my code above, once "Billy Bob" is created you only need to update it, and that include any new service he buy; 这与我上面的代码非常相似,一旦创建了“Billy Bob”,你只需要更新它,包括他购买的任何新服务;

Pseudo code: 伪代码:

var bob = _db.Clients.SingleOrDefault(c=> c.Id = "Bob Row Id")
//Bob buy a car:
bob.Cars.Add(new Car()...)
//...and change tire 1 from an old car
var car = bob.Cars.SingleOrDefault(c=> c.Id = "Car Row Id")
car.TireStatus.Tire1 = "New"
....

//Persist all changes
//Existing objects will be updated..., and the new ones created in this process will be inserted
_db.SaveChanges()

Let me know if this clarify your ideas 如果这澄清了你的想法,请告诉我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架:在Update表中插入外键行 - Entity Framework: Insert foreign key rows when Update table 将列表插入具有外键关系实体框架的多个表中 - Insert list into multiple tables with foreign key relationship Entity Framework 实体框架-使用外键插入 - Entity Framework - Insert with foreign key 实体框架插入到具有外键的主表和子表中 - Entity framework insert to main table and child table having foreign key 使用实体框架使用外键将不同的记录插入表中 - Insert distinct record into table with foreign key using Entity Framework 实体框架将外键更新为null,无需查询且没有相关实体的id - Entity framework update foreign key to null without query and without id of the related entity 如何使用实体框架对与外键相关的多个表执行批量插入 - How to perform bulk insert into multilple tables which are related with foreign keys using entity framework 实体框架-尝试使用外键插入表中,EF尝试使用主键插入原始表中 - Entity Framework - trying to insert into a table with a foreign key, EF attempts to insert into the original table with the primary key 在带有外键的表中添加实体框架中的数据 - Adding data in Entity Framework in tables with Foreign Key 多个表/实体的实体框架外键 - Entity Framework foreign key to multiple tables/entities
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM