上接精进不休 .NET 4.0 (8) - ADO.NET Entity Framework 4.0 Self Tracking Entity

简介:
2、WCF 结合 Self Tracking Entity 的 Demo
服务端:NTierServer/IMyService.cs
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.Text; 

namespace NTierServer 

        [ServiceContract] 
         public interface IMyService 
        { 
                [OperationContract] 
                List<ProductCategory> GetCategories(); 

                [OperationContract] 
                ProductCategory GetCategory(int categoryId); 

                [OperationContract] 
                int UpdateCategory(ProductCategory category); 

                [OperationContract] 
                int AddCategory(ProductCategory category); 

                [OperationContract] 
                int DeleteCategory(int categoryId); 
        } 
}
 
服务端:NTierServer/MyService.cs
/* 
* ADO.NET Entity Framework 4.0 - WCF 结合 Self Tracking Entity 的应用 
*         1、通过 WCF 使用 Self Tracking Entity 不需手动调用 StartTracking() 
*         2、先 MarkAsAdded(), MarkAsModified(), MarkAsDeleted() 再 ApplyChanges() ; 或者 先 ApplyChanges() 再 ChangeObjectState(), ChangeRelationshipState() 
*    
* 本 Demo 演示如何通过 WCF 结合 Self Tracking Entity 来实现对单表的增删改查 
*/ 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.Text; 
using System.Data; 

namespace NTierServer 

         public  class MyService : IMyService 
        { 
                // 取全部产品类别的实体集合 
List<ProductCategory> GetCategories() List<ProductCategory> GetCategories() 
                { 
                        using (var ctx =  new AdventureWorksEntities()) 
                        { 
                                var result = ctx.ProductCategories.ToList(); 
                                return result; 
                        } 
                } 

                // 根据 id 取产品类别实体 
ProductCategory GetCategory() ProductCategory GetCategory(int categoryId) 
                { 
                        using (var ctx =  new AdventureWorksEntities()) 
                        { 
                                var result = ctx.ProductCategories.Single(c => c.ProductCategoryID == categoryId); 
                                return result; 
                        } 
                } 

                // 根据产品类别实体更新数据库中的相关数据 
int UpdateCategory() int UpdateCategory(ProductCategory category) 
                { 
                        using (var ctx =  new AdventureWorksEntities()) 
                        { 
                                // 先 ApplyChanges() 再 ChangeObjectState(), ChangeRelationshipState() 
                                ctx.ProductCategories.ApplyChanges(category); 
                                ctx.ObjectStateManager.ChangeObjectState(category, EntityState.Modified); 

                                return ctx.SaveChanges(); 
                        } 
                } 

                // 根据产品类别实体向数据库添加新的数据 
int AddCategory() int AddCategory(ProductCategory category) 
                { 
                        using (var ctx =  new AdventureWorksEntities()) 
                        { 
                                ctx.ProductCategories.ApplyChanges(category); 
                                return ctx.SaveChanges(); 
                        } 
                } 

                // 根据 id 删除数据库中的相关数据 
int DeleteCategory() int DeleteCategory(int categoryId) 
                { 
                        using (var ctx =  new AdventureWorksEntities()) 
                        { 
                                var category = GetCategory(categoryId); 

                                // 先 MarkAsAdded(), MarkAsModified(), MarkAsDeleted() 再 ApplyChanges() 
                                category.MarkAsDeleted(); 
                                ctx.ProductCategories.ApplyChanges(category); 

                                return ctx.SaveChanges(); 
                        } 
                } 
        } 
}
 
服务端:NTierServer/Web.config
<system.serviceModel> 
        <behaviors> 
                <serviceBehaviors> 
                        <behavior name=""> 
                                <serviceMetadata httpGetEnabled= "true" /> 
                                <serviceDebug includeExceptionDetailInFaults= "true" /> 
                        </behavior> 
                </serviceBehaviors> 
        </behaviors> 
        <serviceHostingEnvironment multipleSiteBindingsEnabled= "true" /> 
</system.serviceModel>
 
客户端:NTierClient/Web.config
<system.serviceModel> 
        <bindings> 
                <basicHttpBinding> 
                        <binding name= "BasicHttpBinding_IMyService" closeTimeout= "00:01:00" 
                                openTimeout= "00:01:00" receiveTimeout= "00:10:00" sendTimeout= "00:01:00" 
                                allowCookies= "false" bypassProxyOnLocal= "false" hostNameComparisonMode= "StrongWildcard" 
                                maxBufferSize= "65536" maxBufferPoolSize= "524288" maxReceivedMessageSize= "65536" 
                                messageEncoding= "Text" textEncoding= "utf-8" transferMode= "Buffered" 
                                useDefaultWebProxy= "true"
                                <readerQuotas maxDepth= "32" maxStringContentLength= "8192" maxArrayLength= "16384" 
                                        maxBytesPerRead= "4096" maxNameTableCharCount= "16384" /> 
                                <security mode= "None"
                                        <transport clientCredentialType= "None" proxyCredentialType= "None" 
                                                realm="" /> 
                                        <message clientCredentialType= "UserName" algorithmSuite= "Default" /> 
                                </security> 
                        </binding> 
                </basicHttpBinding> 
        </bindings> 
        <client> 
                <endpoint address= "http://localhost:10394/MyService.svc" binding= "basicHttpBinding" 
                        bindingConfiguration= "BasicHttpBinding_IMyService" contract= "MyServiceReference.IMyService" 
                        name= "BasicHttpBinding_IMyService" /> 
        </client> 
</system.serviceModel>
 
客户端:NTierClient/Demo.aspx
<%@ Page Language= "C#" AutoEventWireup= "true" CodeBehind= "Demo.aspx.cs"  Inherits= "NTierClient.Demo" %> 

<!DOCTYPE html  PUBLIC  "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
<html xmlns= "http://www.w3.org/1999/xhtml"
<head runat= "server"
        <title></title> 
</head> 
<body> 
        <form id= "form1" runat= "server"
        <div> 
                <asp:ListView ID= "ListView1" runat= "server" DataKeyNames= "ProductCategoryID" InsertItemPosition= "LastItem" 
                        OnItemDeleting= "ListView1_ItemDeleting" OnItemInserting= "ListView1_ItemInserting" 
                        OnItemUpdating= "ListView1_ItemUpdating" OnItemCanceling= "ListView1_ItemCanceling" 
                        OnItemEditing= "ListView1_ItemEditing"
                        <EditItemTemplate> 
                                <tr style=""> 
                                        <td> 
                                                <asp:Button ID= "UpdateButton" runat= "server" CommandName= "Update" Text= "Update" /> 
                                                <asp:Button ID= "CancelButton" runat= "server" CommandName= "Cancel" Text= "Cancel" /> 
                                        </td> 
                                        <td> 
                                                  
                                        </td> 
                                        <td> 
                                                  
                                        </td> 
                                        <td> 
                                                <asp:TextBox ID= "NameTextBox" runat= "server" Text= '<%# Bind("Name") %>' /> 
                                        </td> 
                                        <td> 
                                                  
                                        </td> 
                                        <td> 
                                                  
                                        </td> 
                                </tr> 
                        </EditItemTemplate> 
                        <InsertItemTemplate> 
                                <tr style=""> 
                                        <td> 
                                                <asp:Button ID= "InsertButton" runat= "server" CommandName= "Insert" Text= "Insert" /> 
                                                <asp:Button ID= "CancelButton" runat= "server" CommandName= "Cancel" Text= "Clear" /> 
                                        </td> 
                                        <td> 
                                                  
                                        </td> 
                                        <td> 
                                                  
                                        </td> 
                                        <td> 
                                                <asp:TextBox ID= "NameTextBox" runat= "server" Text= '<%# Bind("Name") %>' /> 
                                        </td> 
                                        <td> 
                                                  
                                        </td> 
                                        <td> 
                                                  
                                        </td> 
                                </tr> 
                        </InsertItemTemplate> 
                        <ItemTemplate> 
                                <tr style=""> 
                                        <td> 
                                                <asp:Button ID= "DeleteButton" runat= "server" CommandName= "Delete" Text= "Delete" /> 
                                                <asp:Button ID= "EditButton" runat= "server" CommandName= "Edit" Text= "Edit" /> 
                                        </td> 
                                        <td> 
                                                <asp:Label ID= "ProductCategoryIDLabel" runat= "server" Text= '<%# Eval("ProductCategoryID") %>' /> 
                                        </td> 
                                        <td> 
                                                <asp:Label ID= "ParentProductCategoryIDLabel" runat= "server" Text= '<%# Eval("ParentProductCategoryID") %>' /> 
                                        </td> 
                                        <td> 
                                                <asp:Label ID= "NameLabel" runat= "server" Text= '<%# Eval("Name") %>' /> 
                                        </td> 
                                        <td> 
                                                <asp:Label ID= "rowguidLabel" runat= "server" Text= '<%# Eval("rowguid") %>' /> 
                                        </td> 
                                        <td> 
                                                <asp:Label ID= "ModifiedDateLabel" runat= "server" Text= '<%# Eval("ModifiedDate") %>' /> 
                                        </td> 
                                </tr> 
                        </ItemTemplate> 
                        <LayoutTemplate> 
                                <table id= "itemPlaceholderContainer" runat= "server" border= "0" style=""> 
                                        <tr runat= "server" style=""> 
                                                <th runat= "server"
                                                </th> 
                                                <th runat= "server"
                                                        ProductCategoryID 
                                                </th> 
                                                <th runat= "server"
                                                        ParentProductCategoryID 
                                                </th> 
                                                <th runat= "server"
                                                        Name 
                                                </th> 
                                                <th runat= "server"
                                                        rowguid 
                                                </th> 
                                                <th runat= "server"
                                                        ModifiedDate 
                                                </th> 
                                        </tr> 
                                        <tr id= "itemPlaceholder" runat= "server"
                                        </tr> 
                                </table> 
                        </LayoutTemplate> 
                </asp:ListView> 
        </div> 
        </form> 
</body> 
</html>
 
客户端:NTierClient/Demo.aspx.cs
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

using System.ServiceModel; 

namespace NTierClient 

         public partial  class Demo : System.Web.UI.Page 
        { 
void Page_Load() void Page_Load(object sender, EventArgs e) 
                { 
                         if (!Page.IsPostBack) 
                        { 
                                BindData(); 
                        } 
                } 

void BindData() void BindData() 
                { 
                        var svc =  new ChannelFactory<MyServiceReference.IMyService>( "BasicHttpBinding_IMyService").CreateChannel(); 

                        var categories = svc.GetCategories(); 
                        ListView1.DataSource = categories; 
                        ListView1.DataBind(); 
                } 

void ListView1_ItemUpdating() void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e) 
                { 
                        var svc =  new MyServiceReference.MyServiceClient(); 
                        var category = svc.GetCategory((int)ListView1.DataKeys[e.ItemIndex].Value); 

                        category.Name = ( string)e.NewValues[ "Name"]; 

                        svc.UpdateCategory(category); 

                        ListView1.EditIndex = -1; 
                        BindData(); 
                } 

void ListView1_ItemInserting() void ListView1_ItemInserting(object sender, ListViewInsertEventArgs e) 
                { 
                        var category =  new MyServiceReference.ProductCategory(); 
                        category.Name = ( string)e.Values[ "Name"]; 
                        category.rowguid = Guid.NewGuid(); 
                        category.ModifiedDate = DateTime.Now; 

                        var svc =  new MyServiceReference.MyServiceClient(); 
                        svc.AddCategory(category); 

                        BindData(); 
                } 

void ListView1_ItemDeleting() void ListView1_ItemDeleting(object sender, ListViewDeleteEventArgs e) 
                { 
                        var svc =  new MyServiceReference.MyServiceClient(); 
                        svc.DeleteCategory((int)ListView1.DataKeys[e.ItemIndex].Value); 

                        BindData(); 
                } 

void ListView1_ItemCanceling() void ListView1_ItemCanceling(object sender, ListViewCancelEventArgs e) 
                { 
                        ListView1.EditIndex = -1; 
                        BindData(); 
                } 

void ListView1_ItemEditing() void ListView1_ItemEditing(object sender, ListViewEditEventArgs e) 
                { 
                        ListView1.EditIndex = e.NewEditIndex; 
                        BindData(); 
                } 
        } 
}
 
 


     本文转自webabcd 51CTO博客,原文链接:http://blog.51cto.com/webabcd/341388 ,如需转载请自行联系原作者

相关文章
|
1月前
|
XML 开发框架 .NET
C# .NET面试系列八:ADO.NET、XML、HTTP、AJAX、WebService
## 第二部分:ADO.NET、XML、HTTP、AJAX、WebService #### 1. .NET 和 C# 有什么区别? .NET(通用语言运行时): ```c# 定义:.NET 是一个软件开发框架,提供了一个通用的运行时环境,用于在不同的编程语言中执行代码。 作用:它为多语言支持提供了一个统一的平台,允许不同的语言共享类库和其他资源。.NET 包括 Common Language Runtime (CLR)、基础类库(BCL)和其他工具。 ``` C#(C Sharp): ```c# 定义: C# 是一种由微软设计的面向对象的编程语言,专门为.NET 平台开发而创建。 作
174 2
|
2月前
|
SQL 开发框架 .NET
ASP.NET WEB+EntityFramework数据持久化——考核练习库——1、用户管理系统(考点:查询列表、增加、删除)
ASP.NET WEB+EntityFramework数据持久化——考核练习库——1、用户管理系统(考点:查询列表、增加、删除)
67 0
|
4月前
|
存储 开发框架 .NET
Asp.net就业课之Ado.net第一次课
Asp.net就业课之Ado.net第一次课
21 0
|
开发框架 .NET 数据库
ASP.NET Core Identity自定义数据库结构和完全使用Dapper而非EntityFramework Core
ASP.NET Core Identity自定义数据库结构和完全使用Dapper而非EntityFramework Core前言原本本节内容是不存在的,出于有几个人问到了我:我想使用ASP.NET Core Identity,但是我又不想使用默认生成的数据库表,想自定义一套,我想要使用ASP.NE Core Identity又不想使用EntityFramework Core。
1017 0
|
存储 .NET 关系型数据库
.net core Entity Framework 与 EF Core
重点讲 Entity Framework Core ! (一)Entity Framework            它是适用于.NET 的对象关系映射程序 (ORM),现在的EF6已经是久经沙场,并经历重重磨难,获得一致认可的数据访问技术(原来加 Title 也挺有意思的,哈哈哈)。
1547 0
|
SQL 前端开发 .NET
Asp.net 面向接口可扩展框架之数据处理模块及EntityFramework扩展和Dapper扩展(含干货)
原文:Asp.net 面向接口可扩展框架之数据处理模块及EntityFramework扩展和Dapper扩展(含干货) 接口数据处理模块是什么意思呢?实际上很简单,就是使用面向接口的思想和方式来做数据处理。
1136 0
|
SQL .NET 数据库
ASP.NET Core 配置 Entity Framework Core - ASP.NET Core 基础教程 - 简单教程,简单编程
原文:ASP.NET Core 配置 Entity Framework Core - ASP.NET Core 基础教程 - 简单教程,简单编程 ASP.NET Core 配置 Entity Framework Core 上一章节学习完了视图,其实我们应该立即着手讲解模型的,但 ASP.
1454 0
|
.NET 数据库 开发框架
ASP.NET CORE系列【二】使用Entity Framework Core进行增删改查
原文:ASP.NET CORE系列【二】使用Entity Framework Core进行增删改查 介绍 EntityFrameworkCore EF core 是一个轻量级的,可扩展的EF的跨平台版本。
1618 0
|
.NET 开发框架 中间件
ASP.NET CORE系列【三】使用Entity Framework Core进行增删改查
原文:ASP.NET CORE系列【三】使用Entity Framework Core进行增删改查 身份验证 以前我们熟悉的web.config中配置的form验证,现在没有了。我们来看看在Core里面如何配置; 首先需要NuGet安装一个包:Microsoft.
1752 0