简体   繁体   English

C#:在数据库优先设置中初始化和种子

[英]C#: Initialize and Seed in a Database First setup

So I am working with EF6 and I have a Database First setup. 因此,我正在使用EF6,并且具有数据库优先设置。 I'm looking to populate my database with some data of course, but I can't seem to find out how. 我当然想用一些数据填充我的数据库,但是我似乎找不到方法。 The bulk of the documentation concerns performing such operations in a Code First setup, but I don't have any of those. 文档中的大部分内容涉及在“代码优先”设置中执行此类操作,但是我没有任何这些。

My question is, given a Database First setup, how do I go about seeding my db with data? 我的问题是,给定“数据库优先”设置,如何为数据库播种数据?

Any help is greatly appreciated. 任何帮助是极大的赞赏。

Database First means that you create a DB and then generate some models depending on it. 数据库优先意味着您创建一个数据库,然后根据它生成一些模型。 You should either seed data on your own or switch to the Code First. 您应该自己播种数据或切换到“代码优先”。

You can write your own initializer but I am not sure whether it is something you are looking for. 您可以编写自己的初始化程序,但不确定是否要查找它。

In your first launch or, at the end of application installation you can use your data access layer or repository layer and populate your data. 在首次启动时或在应用程序安装结束时,您可以使用数据访问层或存储库层并填充数据。

Because this is seeding, you might see some scenarios, that you should bypass, some validation. 因为这是种子,所以您可能会看到一些应该绕过的场景以及一些验证。 That's why I suggest to use your DAL/Repository instead of your service later. 这就是为什么我建议以后使用您的DAL /存储库而不是您的服务的原因。

For example, simply create a class called, DatabaseSetup and a static method like Provision, and create every object you need then push them to database. 例如,只需创建一个名为DatabaseSetup的类和一个诸如Provision的静态方法,然后创建所需的每个对象,然后将它们推入数据库即可。 Alternatively, you can read the initial data from JSON file if the seed data is variable based on different scenarios. 或者,如果种子数据根据不同的场景是可变的,则可以从JSON文件读取初始数据。

All in all, I wasn't able to find a way to seed my db with a Database First setup. 总而言之,我找不到使用Database First设置为我的数据库添加种子的方法。 I ended up refactoring my data layer to use Code First, and I can't say that I miss the DB First method. 我最终重构了数据层以使用Code First,但我不能说我错过了DB First方法。

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

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