简体   繁体   English

实体框架将记录添加到表中

[英]Entity Framework add records to table

I will start by saying I am new to Entity Framework and am still learning about the concepts. 我将首先说我是Entity Framework的新手,我仍在学习这些概念。

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. 这是一个基本表,应该只有3个条目,这些条目将在创建表时添加一次,然后不再编辑或删除。

Aside from loading SQL server and writing insert statements myself, is there a way to add these entries with entity framework? 除了自己加载SQL服务器和编写插入语句之外,有没有办法用实体框架添加这些条目?

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. 我可以在我的代码中的某处编写一些insert语句,但在我看来,在现有框架中应该有一些安全的方法。

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 https://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-3使用代码优先迁移为种子数据库设定种子

You can use migrations or the DbContext initializer for this. 您可以使用迁移或DbContext初始化程序。 Search on entity framework seed . 搜索实体框架种子

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

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

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