简体   繁体   中英

Entity Framework add records to table

I will start by saying I am new to Entity Framework and am still learning about the concepts.

I have the following Model:

public class AppProduct
{
    public int Id { get; set; }

    public string Product { get; set; }

}

Which I then add to the context as follows:

public virtual DbSet<AppProduct> AppProducts { get; set; }

This is a basic table that should only have 3 entries which will be added once when the table is created and then not edited or deleted from then on.

Aside from loading SQL server and writing insert statements myself, is there a way to add these entries with entity framework?

I could write some insert statement in my code somewhere, but it seems to me that there should be some safe way of doing this within the existing framework.

I am thinking along the lines of adding insert statements to the migration file?

Searching for terms like add entry once using entity framework does not provide any answer that seem to address this issue.

If you are still looking for how to seed your table, This is a good tutorial on how to do with a good example. Please take a look once.

https://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-3 Use Code First Migrations to Seed the Database

You can use migrations or the DbContext initializer for this. Search on entity framework seed .

为AppProduct表使用单独的DbContext(仅启用其他DbContext的迁移)。

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