简体   繁体   中英

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.

Assuming you just want to create a new entity representing a table in the database, you can use this procedure from another SO question . 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 ). 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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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