访问使用C#.NET SQL Server数据库的最佳方式方式、数据库、NET、SQL

2023-09-04 00:08:16 作者:ら゛浅安时光

我是新来的.NET和听到有关查询一个SQL Server DATABSE诸如ADO.NET和实体框架的几种不同的方法。

I am new to .NET and have heard about several different ways of querying a SQL Server databse such as ADO.NET and the entity framework.

谁能给我一些建议即将去新的应用程序的最佳方法是什么?

Can anyone give me some advise about the best way to go for new applications?

感谢您的任何帮助或建议。

Thanks for any help or suggestions.

推荐答案

下面是一个使用EF与code一代从数据库中(对于一个真正的应用程序,你可能想要生成从code你的数据库的一个例子,代替):

Here is an example using EF with code generation from the database (for a real app you probably want to generate your DB from the code, instead):

右键点击您的项目>>添加>>新产品>> ADO.NET实体数据模型。 选择一个名称为您的实体,即MyEntities.edmx,单击Next 选择从数据库生成 配置新建连接如果没有一个已经存在。下一步。 选择表,视图,和的存储过程要包括在实体。完成。

您会看到一个文件MyEntities.edmx添加到项目中。您可以在设计视图中打开它,看看你的实体和关系的示意图。请注意,每个实体都应有一个主键 - 要做到这一点最简单的方法是将一个ID添加 - 自动递增字段每个表,或GUID列。反正现在你可以查询你的数据库是这样的:

You will see a file MyEntities.edmx added to your project. You can open it in design view to see a diagram of your entities and relationships. Note that each entity should have a primary key - the easiest way to do this is to add an ID - auto increment field to each table, or a GUID column. Anyway now you can query your db like this:

// assuming a "Product" table, which has an entity pluralized to "Products"

MyEntities db = new MyEntities();

var cheapProducts = db.Products.Where(p => p.Price > 30); // var is IEnumerable<Product>