简体   繁体   English

从Entity Framework模型类访问数据库上下文

[英]Access database context from Entity Framework model class

Usually, I create new database entites with dbContext.MyClass.Create() . 通常,我使用dbContext.MyClass.Create()创建新的数据库dbContext.MyClass.Create() In my current application, I need to create such an entity from within an extension method of another model class. 在当前应用程序中,我需要从另一个模型类的扩展方法中创建这样的实体。

I have the two classes DataEntry and WorkSchedule , where one DataEntry can contain multiple WorkSchedules. 我有两个类DataEntryWorkSchedule ,其中一个DataEntry可以包含多个WorkSchedules。 Therefore, I added a method DataEntry.FillOrUpdateFromWCF() , which calls a web service and updates some fields. 因此,我添加了方法DataEntry.FillOrUpdateFromWCF() ,该方法调用Web服务并更新一些字段。 So far, so good. 到现在为止还挺好。

This method also needs to create new WorkSchedules for this same DataEntry in some cases. 在某些情况下,此方法还需要为此相同的DataEntry创建新的WorkSchedules。 The problem is, that I, as far as I know, have no reference to the current DataEntry's database context. 问题是,据我所知,我没有引用当前DataEntry的数据库上下文。 Sure, I could just create them with new WorkSchedule() , but that would not update them after saving, right? 当然,我可以使用new WorkSchedule()创建它们,但是保存后不会更新它们,对吗?

So is there something like a this.ThisEntitysDatabaseContext.WorkSchedule.Create() method from within the DataEntry class? 那么在DataEntry类中是否有类似this.ThisEntitysDatabaseContext.WorkSchedule.Create()方法的东西?

public partial class DataEntry {
  public async Task FillOrUpdate() {
    WcfData[] data = GetSomeDataFromWCF();

    foreach(WcfData wd in data) {
      WorkSchedule ws = this.PathToContext.WorkSchedule.Create();
      ws.Stuff = "test";
      this.WorkSchedules.Add(ws);
    }
  }
}

Sure, I could just create them with new WorkSchedule(), but that would not update them after saving, right? 当然,我可以使用新的WorkSchedule()创建它们,但是保存后不会更新它们,对吗?

It would, as long as you attach them to a tracked entity. 只要您将它们附加到跟踪的实体,它就会。 You really don't want access to the DbContext in an entity class, that's an antipattern. 您确实不希望在实体类中访问DbContext,这是一种反模式。 You also should reconsider whether you want your entity classes to contain any logic, but that's up for debate. 您还应该重新考虑是否要让您的实体类包含任何逻辑,但这尚需辩论。

So if you have something like this: 因此,如果您有这样的事情:

public class DataEntry
{
    public ICollection<WorkSchedule> Schedules { get; set; }

    public void DoWork()
    {
        Schedules.Add(new WorkSchedule
        {
            Start = DateTime.Now
        });
    }
}

Then this will add the proper record and foreign key (assuming that's all set up properly): 然后,这将添加适当的记录和外键(假设所有设置均正确):

using (var db = new YourContext())
{
    var dataEntry = db.DataEntries.Single(d => d.Id == 42);

    dataEntry.DoWork();

    db.SaveChanges();
}

Actually, you don't need to ask the DbContext to Create a DataEntry for you. 实际上,您不需要让DbContext为您创建一个DataEntry。 In fact, this is quite uncommon. 实际上,这种情况并不常见。

Usually you create the object using new , then fill all the properties, except the primary keys and Add the object to the dbContext 通常,您使用new创建对象,然后填充除主键之外的所有属性,然后将对象AdddbContext

using (var dbContext = new MyDbContext())
{

     DataEntry entryToAdd = new DataEntry()
     {
          // fill the properties you want, leave the primary key zero (default value)
          Name = ...
          Date = ...

          WorkShedules = ...
     };

     // add the DataEntry to the database and save the changes
     dbContext.Add(entryToAdd);
     dbContext.SaveChanges();
}

For the WorkSchedules you can use your own function, but you can also assign a value using operator new: 对于WorkSchedules您可以使用自己的函数,但也可以使用运算符new来分配值:

WorkSchedules = new List<WorkSchedule>()
{
    new WorkSchedule() {Name = "...", ...},
    new WorkSchedule() {Name = "...", ...},
    new WorkSchedule() {Name = "...", ...},
},

Note: do not fill the primary key of the work schedule, nor the foreign key of the DataEntry that this Workschedule belongs to, after all, you don't know the value yet. 注意:请不要填写工作计划的主键,也不要填写此Workschedule所属的DataEntry的外键,毕竟您还不知道该值。

Entity framework is smart enough to understand the one-to-many relationship, and will add the proper items to the database, with the proper values for the foreign keys. 实体框架足够聪明,可以理解一对多的关系,并将适当的项目添加到数据库中,并带有适当的外键值。

暂无
暂无

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

相关问题 来自模型的Entity Framework数据库 - Entity Framework database from a model 处置上下文后,如何从实体框架(数据库优先)返回包含导航属性的模型? - How do I return a Model from Entity Framework (Database First) that includes the Navigation Properties after the context is disposed? 实体框架上下文和 model inheritance 在数据库第一种方法中搭建脚手架时 - Entity Framework context and model inheritance when scaffolding in database first approach 实体框架不会从 MVC 中的实体数据模型(来自现有数据库)创建上下文和表类(.cs) - Entity Framework doesn't create Context and table classes(.cs) from Entity Data Model (from existing database) in MVC 实体框架不会将数据库上下文中仍然存在的对象与从不同类引用的同一对象相关联 - Entity Framework doesn't associate a still existing object in the database context with the same object referenced from a different class 实体框架核心-如何访问Context.Database.Migrate() - Entity Framework Core - How To Access Context.Database.Migrate() 如何在实体框架中访问context.Database.SqlQuery? - How to access context.Database.SqlQuery in Entity Framework? 来自数据库问题的实体框架更新模型 - Entity Framework update model from database issue 从实体框架模型生成数据库 - Generating database from entity framework model 在实体框架中从数据库更新模型不起作用 - Update model from database in entity framework is not working
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM