一步一步学Linq to sql(九):其它补充

外部映射文件

我们可以使用sqlmetal命令行工具来生成外部映射文件,使用方法如下:

1. 开始菜单 -》 VS2008 -》VS工具 -》VS2010命令行提示

2、输入命令:

sqlmetal  /conn:server=.;database=pubs;uid=sa;pwd=saa /map:c:\pub.map  /code:c:\pubs.cs

3.这样,我们就可以在C盘下得到一个xml映射文件和C#的实体类代码

4.把.cs文件添加到项目中来,然后使用下面的代码加载映射文件:

            string path = @"C:\pub.map";
            XmlMappingSource xms = XmlMappingSource.FromXml(File.ReadAllText(path));
            Pubs ctx = new Pubs("server=.;database=pubs;uid=sa;pwd=saa", xms);

5、现在就可以照常进行其它工作了。使用sqlmetal可以很方便的同步数据库与实体和映射文件。每次修改数据库结构,从dbml设计器上删除表、存储过程然后再重新添加也是很麻烦的事情。

处理空值

            var count = (from c in ctx.Authors where c.City == null select c).Count();
            Console.WriteLine(count.ToString());
            Console.ReadLine();

已编译查询

            var author = from au in ctx.Authors select au;
            Console.WriteLine("Provider类型:"+ctx.Mapping.ProviderType);
            Console.WriteLine("数据库:" + ctx.Mapping.DatabaseName);
            Console.WriteLine("表:" + ctx.Mapping.GetTable(typeof(Authors)).TableName);
            Console.WriteLine("表达式:" + author.Expression.ToString());
       Console.WriteLine("sql:" + author.Provider.ToString());

撤销提交

            var author1 = ctx.Authors.Single(c => c.Au_lname == "Bennet");
            author1.City = "深圳";
            author1.Address = "广东";

            Console.WriteLine("省份" + author1.Address + "城市" + author1.City);
            author1 = ctx.Authors.GetOriginalEntityState(author1);
            Console.WriteLine("省份" + author1.Address + "城市" + author1.City);

批量操作

下面的代码会导致提交N次DELETE操作:

            var query1 = from c in ctx.Authors select c;

            ctx.Authors.DeleteAllOnSubmit(query1);

            ctx.SubmitChanges();

应该使用sql语句进行批操作:

            string sql = String.Format("delete from {0}", ctx.Mapping.GetTable(typeof(Authors)).TableName);

            ctx.ExecuteCommand(sql);

  对于批量更新操作也是同样道理。

转载于:https://www.cnblogs.com/aehyok/archive/2013/04/23/3038321.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值