木子屋 Dnawo's BLOG

SQL Server数据库ADO.NET实体数据模型使用示例

👤 dnawo 📅 2012-08-29 👁 5493 👍 0 💬 0 🔄 本站原创
一、添加SQL Server数据库ADO.NET实体数据模型

①.添加新项并选择"ADO.NET实体数据模型":
图片

②.选择从数据库生成模型:
图片

③.设置数据库连接:
图片

④.选择要在模型中包含的数据库对象,点击完成生成实体数据模型:
图片

二、将存储过程转为函数

打开模型浏览器,右键点击需要使用的存储过程,在菜单中选择添加函数导入:

图片

图片

三、ADO.NET 实体数据模型使用示例

①.增加记录:
using (NorthwindEntities northwind = new NorthwindEntities())
{
    Categories entity = new Categories();
    entity.CategoryName = "fruit";
    entity.Description = "-";
    northwind.Categories.AddObject(entity);
    northwind.SaveChanges();
}

SQL Server Profiler跟踪结果:
exec sp_executesql N'insert [dbo].[Categories]([CategoryName], [Description], [Picture])
values (@0, @1, null)
select [CategoryID]
from [dbo].[Categories]
where @@ROWCOUNT > 0 and [CategoryID] = scope_identity()',N'@0 nvarchar(15),@1 nvarchar(max) ',@0=N'fruit',@1=N'-'

②.修改记录:
using (NorthwindEntities northwind = new NorthwindEntities())
{
    Categories entity = northwind.Categories.First(e => e.CategoryName == "fruit");
    entity.Description = "fruit description.";
    northwind.SaveChanges();
}

SQL Server Profiler跟踪结果:
exec sp_executesql N'update [dbo].[Categories]
set [Description] = @0
where ([CategoryID] = @1)
',N'@0 nvarchar(max) ,@1 int',@0=N'fruit description.',@1=24

说明:不是全部字段值提交到服务器,仅提交修改部分!

③.删除记录:
using (NorthwindEntities northwind = new NorthwindEntities())
{
    Categories entity = northwind.Categories.First(e => e.CategoryName == "fruit");
    northwind.Categories.DeleteObject(entity);
    northwind.SaveChanges();
}

SQL Server Profiler跟踪结果:
exec sp_executesql N'delete [dbo].[Categories]
where ([CategoryID] = @0)',N'@0 int',@0=24

④.查询记录:
using (NorthwindEntities northwind = new NorthwindEntities())
{
    var categories = northwind.Categories;
    foreach (var item in categories)
        Console.WriteLine("{0},{1}", item.CategoryName, item.Description);
}

SQL Server Profiler跟踪结果:
Select
[Extent1].[CategoryID] AS [CategoryID],
[Extent1].[CategoryName] AS [CategoryName],
[Extent1].[Description] AS [Description],
[Extent1].[Picture] AS [Picture]
FROM [dbo].[Categories] AS [Extent1]

⑤.调用存储过程:
using (NorthwindEntities northwind = new NorthwindEntities())
{
    var query = northwind.CustOrdersDetail(10284);
    foreach (var item in query)
        Console.WriteLine("{0},{1}", item.ProductName, item.ExtendedPrice);
}

SQL Server Profiler跟踪结果:
exec [dbo].[CustOrdersDetail] @OrderID=10284

评论(0)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 只可添加来自Chrome网上应用店的扩展程序、应用和用户脚本 下一篇 → 实体数据模型(EDM)加入导航属性序列化失败解决方法