简体   繁体   English

如何手动更新实体框架中的实体

[英]How to update entity in entity-framework manually

I have a project used entity framework, and now I want to add a new entity to the framework, the database have some slight changes which don't influence the code, however, if I want to add a new entity by update wizard the changes will be implemented too and errors will be thrown. 我有一个项目使用的实体框架,现在我想向该框架中添加一个新的实体,数据库做了一些细微的更改,这些更改不会影响代码,但是,如果我想通过更新向导添加一个新的实体,则更改也会实现,并且会引发错误。 I think the only way is to add entity manually, but I don't know how to do it. 我认为唯一的方法是手动添加实体,但是我不知道该怎么做。

You should use partial classes for your own code when using Entity Framework with a Model. 当将实体框架与模型一起使用时,应为自己的代码使用部分类。 In the partial classes you put in your code (so when you update the Model you won't loose it). 在部分类中,您放入了代码(因此,在更新模型时,您不会丢失它)。 I would recommend that you update your model and fix the errors, because you will have to update it more often in the future and you don't want to write the xml manually on every change. 我建议您更新模型并修复错误,因为将来您将不得不更频繁地更新它,并且您不想在每次更改时都手动编写xml。

Assuming you just want to create a new entity representing a table in the database, you can use this procedure from another SO question . 假设您只想创建一个表示数据库中表的新实体,则可以使用另一个SO问题中的此过程 That should provide you with a new entity class generated from only one of the tables while ignoring the rest of the DB. 这应该为您提供一个仅由一个表生成的新实体类,而忽略了数据库的其余部分。

Update, in answer to a question below: 更新,回答以下问题:

If you are able to create the entity class, but it does not show up where you need it, make sure you've added it in your Context (there should be a class which inerits DbContext ). 如果您能够创建实体类,但未在需要的地方显示它,请确保已将其添加到Context (应该有一个继承DbContext的类)。 Look for something like: 寻找类似的东西:

public DbSet<SomeExistingEntityClass> SomeExistingEntityClass1 { get; set; }
public DbSet<SomeExistingEntityClass> SomeExistingEntityClass2 { get; set; }
...
public DbSet<YourEntityClass> YourEntityClass { get; set; } // <-- Add this

You might also need to add a configuration for your new entity. 您可能还需要为新实体添加配置 There are several ways to do this; 做这件事有很多种方法; in my case, configs are specified like this in the context class: 就我而言,配置是在context类中指定的:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new SomeExistingEntityClass1Config());
    modelBuilder.Configurations.Add(new SomeExistingEntityClass2Config());
    ....
    modelBuilder.Configurations.Add(new MyEntityClassConfig()); // <-- Add this
}

..and then the config class itself looks like: ..,然后config类本身看起来像:

public class MyEntityClassConfig : EntityTypeConfiguration<MyEntityClassConfig>
{
    public MyEntityClassConfig()
    {
        ToTable("My_Database_Table_Name");
        HasKey(table => table.Name_of_primary_key);
    }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM