在写LINQ语句的时候,往往会看到.AsEnumerable() 和 .AsQueryable() 。 例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
string strcon = "Data Source=.\\SQLEXPRESS;Initial Catalog=Db_Example;Persist Security Info=True;User ID=sa;Password=sa"; SqlConnection con = new SqlConnection(strcon); con.Open(); string strsql = "select * from SC,Course where SC.Cno=Course.Cno"; SqlDataAdapter da = new SqlDataAdapter(strsql,con); DataSet ds = new DataSet(); da.Fill(ds, "mytable"); DataTable tables=ds.Tables["mytable"]; //创建表 var dslp = from d in tables<strong>.AsEnumerable()</strong> select d;//执行LINQ语句,这里的.AsEnumerable()是延迟发生,不会立即执行,实际上什么都没有发生 foreach(var res in dslp) { Response.Write(res.Field<string>("Cname").ToString()); } |
上述代码使用LINQ 针对数据集中的数据进行筛选和整理,同样能够以一种面向对象的思想进行数据集中数据的筛选。在使用LINQ 进行数据集操作时,LINQ 不能直接从数据集对象中查询,因为数据集对象不支持LINQ 查询,所以需要使用AsEnumerable 方法返回一个泛型的对象以支持LINQ 的查询操作。 .AsEnumerable()是延迟执行的,实际上什么都没有发生,当真正使用对象的时候(例如调用:First, Single, ToList….的时候)才执行。 下面就是.AsEnumerable()与相对应的.AsQueryable()的区别: AsEnumerable将一个序列向上转换为一个IEnumerable, 强制将Enumerable类下面的查询操作符绑定到后续的子查询当中。 AsQueryable将一个序列向下转换为一个IQueryable, 它生成了一个本地查询的IQueryable包装。 .AsEnumerable()延迟执行,不会立即执行。当你调用.AsEnumerable()的时候,实际上什么都没有发生。 .ToList()立即执行 当你需要操作结果的时候,用.ToList(),否则,如果仅仅是用来查询不需要进一步使用结果集,并可以延迟执行,就用.AsEnumerable()/IEnumerable /IQueryable .AsEnumerable()虽然延迟执行,但还是访问数据库,而.ToList()直接取得结果放在内存中。比如我们需要显示两个部门的员工时,部门可以先取出放置在List中,然后再依次取出各个部门的员工,这时访问的效率要高一些,因为不需要每次都访问数据库去取出部门。 IQueryable实现了IEnumberable接口。但IEnumerable<T> 换成IQueryable<T>后速度提高很多。原因: IQueryable接口与IEnumberable接口的区别: IEnumerable<T> 泛型类在调用自己的SKip 和 Take 等扩展方法之前数据就已经加载在本地内存里了,而IQueryable<T> 是将Skip ,take 这些方法表达式翻译成T-SQL语句之后再向SQL服务器发送命令,它并不是把所有数据都加载到内存里来才进行条件过滤。 IEnumerable跑的是Linq to Object,强制从数据库中读取所有数据到内存先。 from:http://www.cnblogs.com/jianglan/archive/2011/08/11/2135023.html
View Details说明: 请求验证过程检测到有潜在危险的客户端输入值,对请求的处理已经中止。 该值可能指示存在危及应用程序安全的尝试,如跨站点脚本攻击。若要允许页面重写应用程序请求验证设置, 请将 httpRuntime 配置节中的 requestValidationMode 特性设置为 requestValidationMode="2.0"。 示例: <httpRuntime requestValidationMode="2.0" />。设置此值后,可通过在 Page 指令或 <pages> 配置节中设置 validateRequest="false" 禁用请求验证。但是,在这种情况下,强烈建议应用程序显式检查所有输入。 有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkId=153133。 异常详细信息: System.Web.HttpRequestValidationException: 从客户端(myname="<p>test</p>")中检测到有潜在危险的 Request.Form 值。 如果一定要输入含标记的内容,解决方法: (1)修改web.config <system.web> ….. <httpRuntime requestValidationMode="2.0" /> </system.web> (2)Controller中添加[ValidateInput(false)] 例如: [ValidateInput(false)] public ActionResult SendData() { …. } from:http://blog.csdn.net/lanse_my/article/details/38023955
View Details【分部视图】 ASP.NET MVC 里的部分视图,相当于 Web Form 里的 User Control。我们的页面往往会有许多重用的地方,可以进行封装重用。使用 部分视图 : 1. 可以简写代码。2. 页面代码更加清晰、更好维护。 【如何使用】 在视图里有多种方法可以 加载部分视图,包括: Partial() Action() RenderPartial() RenderAction() RenderPage() 方法。 以下是这些方法的差别: Partial 与 RenderPartial 方法 1. Razor 语法:@Html.Partial() 与 @{Html.RenderPartial();} 2. 区别:Partial 可以直接输出内容,它内部是 将 html 内容转换为 string 字符(MVCHtmlString),然后缓存起来, 最后在一次性输出到页面。显然,这个转换的过程,会降低效率,所以通常使用 RenderPartial 代替。 RenderPartial 与 RenderAction 方法 1. Razor 语法:@{Html.RenderPartial();} 与 @{Html.RenderAction();} 2. 区别:RenderPartial 不需要创建 Controller 的 Action ,而 RenderAction 需要在 Controller 创建要加载的 Action。 RenderAction 会先去调用 Contorller 的 Action ,最后再 呈现视图,所以这里 页面会在 发起一个链接。 如果这个部分视图只是一些简单 的 html 代码,请使用 RenderPartial。 但如果这个部分视图 除了有 html 代码外, 还需要 通过 读取数据库里的数据 来渲染,就必须使用 RenderAction […]
View Details1:添加记录后,如何获取新添加的ID的值 比如,一个实体 TestEntity 对应一个表TestEntity(ID主键自增,Name,age),使用linq to ef 添加一条记录后,如何获取新记录的ID值?如下代码:
1 |
var te = new TestEntity () { Name = "名字", Age = 21 }; using (EFDbContext context = new EFDbContext()) { context.TestEntity .Add(te); context.SaveChanges(); return te.ID; } |
调用SaveChanges()之后,ef.ID的值就是数据库中新加记录对应自增标识列的值。Linq to ef智能地判断出ID就是自增主键标识列。 他给我们返回了。 2:列名叫“ID”的列,它不是自增列,linq to ef不让插入的问题 如标题,就是,列名叫“ID”的列,它不是主键,也不是主键,linq to ef不让插入。我已经给ID赋值了 但它一直提示 ID不能为NULL ,打断点,看了,也有值! 代码走到SaveChanges(),就报异常,提示ID不能为空!超蛋疼… 原因:默认情况,linq to ef认为只要实体类中有ID属性,数据库对应的是一定是自增标识列。 解决方式: 1)第一步 因为EFDbContex继承自Context类,所以,我们需要从新对它这个叫OnModelCreating的虚函数进行实现
1 |
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<TestEntity>().Property(p => p.ID) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); } |
2)第二步 在实体类叫ID的属性上加标记实现(记得添加引用):
1 |
public class TestEntity { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int ID { get; set; } public string Name { get; set; } public int Age { get; set; } } |
from:http://www.ithao123.cn/content-2766171.html
View Details准备一些测试数据,如下: use Test Create table Student( ID int identity(1,1) primary key, [Name] nvarchar(50) not null ) Create Table Book( ID int identity(1,1) primary key, [Name] nvarchar(50)not null, StudentID int not null ) insert into Student values('张三') insert into Student values('李四') insert into Student values('王五') select * from student --张三借的书 insert into Book values('红楼',1) insert into Book values('大话红楼',1) --李四借的书 insert into Book values('三国',2) --王五没借书 --一本错误的记录 insert into Book values('错误时怎样练成的',111) --左连接 select s.name,b.name from student as s left join Book as b on s.id=b.studentid --右连接 select s.name,b.name from student […]
View Detailsusing System; using System.Data; using System.Configuration; using System.Collections; using System.Drawing; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class study_CheckCode2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string code = CreateVerifyCode(); //取随机码 CreateImageOnPage(code, this.Context); // 输出图片 Response.Cookies.Add(new HttpCookie("CheckCode", code.ToUpper()));// 使用Cookies取验证码的值 } #region 验证码长度(默认4个验证码的长度) int length = 4; public int Length { get { return length; } set { length = value; } } #endregion […]
View Details
1 2 3 4 5 6 7 |
static List<T> GetPageList(Func<T,bool> whereLambda,Func<T,object> orderLambda,int pageSize,int pageIndex) where T:class { EFEntities context=new EFEntities();//实例化上下文 var list=context.Set<T>().where(whereLambda).orderByDescending(orderLambda).Skip((pageIndex-1)*pageSize).Take(pageSize).Select(s=>s); return list.ToList(); } |
完善后
1 2 3 4 5 6 7 8 9 |
//EF lanbda 分页 public List<dynamic> getPageDate<T, TKey>(Expression<Func<T, dynamic>> select, Expression<Func<T, bool>> where, Expression<Func<T, TKey>> order, int pageIndex, int pageSize, out int Total) where T : class { CIK_NewsEntities db = new CIK_NewsEntities(); Total = db.Set<T>().Where(where).Count(); var list = db.Set<T>().Where(where).OrderByDescending(order).Select(select).Skip((pageIndex - 1) * pageSize).Take(pageSize); return list.ToList(); } |
使用:
1 2 3 4 |
int Total_ = 0; rptCate.DataSource = getPageDate<Category, int>(c => new { c.Name, c.CreatedDate, c.CreatedBy }, c => c.Id > 0, c => c.Id, 2, 4, out Total_); rptCate.DataBind(); this.Label1.Text = Total_.ToString(); |
FROM:http://www.cnblogs.com/juexin/p/4273490.html
View Details又来一篇,大家也许都嫌烦了。但是写博客既能提高自己,又能帮助别人,而且每次写的过程中和发布出来之后都有收获,真是太赚了!麻烦大家忍一忍吧。 言归正题,在之前的一篇随笔“准备用Entity Framework实现数据的按需更新”中,我们实现了按需更新,但和这里的指定字段更新的应用场景不一样。 之前的按需更新的应用场景是:把需要更新与不需要更新的数据都给Entity Framework,由EF自己判断实际需要更新哪些。 现在的应用场景是:我明确知道要更新哪个字段,让EF做的只是更新这个操作,其他不用操心。 下面我们通过一个比喻来比较一下两者的区别。 比如我有一辆车想在汽车修理店更换一些部件。我把车停在车库里,来到修理间。这时,我就不能再直接接触这部车,必须通过修理间的工作人员。工作人员给我一个汽车模型,我有任何更换部件的想法,只能通过这个模型告诉他。 对应于第一种按需更新的场景,我不知道汽车需要实际更换哪些部件,我只知道更换后应该是什么样的。 流程是: 1. 告诉工作人员车牌号码,让他按照我放在车库中的汽车,制作一个一模一样的模型。 2. 工作人员把制作好的模型交给我。 3. 我在这个汽车模型的基础上修改成我想要的样子(但我不知道哪些部件要换,哪些部件不要换)。 4. 把修改好的汽车模型交给工作人员,让他去修理就行了。 5. 我悠然自得地去逛街,不用操心任何事。 对应于第二种根据指定字段更新的场景,我要更换前车灯,汽车修理店你不用管前车灯有没有坏,我就是要换,就是想让你们挣钱。 流程是: 1. 我随手从旁边拿了一个空汽车模型,修改为我想要的前车灯。 2. 把这个汽车模型交给工作人员,让他去修理就行了。 3. 我悠然自得地去逛街,不用操心任何事。 对于第二种场景,如果我们采用第一种场景的操作流程,工作人员累,效率低,费用自然也高。用第二个流程是必然的选择。 今天,我们终于找到了针对第二个流程的解决方法。 比如,我们要更新某个Blog的上次更新时间,我们只需要: 1. 新建一个Blog实体对象,告诉他要更新的Blog的ID以及“上次更新时间”。 2. 把这个实体对象交给Entity Framework,让他完成更新。 代码如下: public void UpdateBlogCoinfigLastUpdatedTest() { using (BlogDbContext context = new BlogDbContext()) { var blog = new Blog() { BlogID = 0, LastModified = DateTime.Now }; context.BlogConfigs.Attach(blog); var stateEntry = ((IObjectContextAdapter)context).ObjectContext. ObjectStateManager.GetObjectStateEntry(blog); stateEntry.SetModifiedProperty("LastUpdated"); context.SaveChanges(); } } EF生成的SQL语句如下: exec sp_executesql N’update [dbo].[blog_Config] set [LastUpdated] = @0 where ([BlogID] = @1) ',N’@0 datetime2(7),@1 int',@0=’2011-04-06 14:12:28.2129938′,@1=0 […]
View Details今天谈谈在.net中读写config文件的各种方法。 在这篇博客中,我将介绍各种配置文件的读写操作。 由于内容较为直观,因此没有过多的空道理,只有实实在在的演示代码, 目的只为了再现实战开发中的各种场景。希望大家能喜欢。 通常,我们在.NET开发过程中,会接触二种类型的配置文件:config文件,xml文件。 今天的博客示例也将介绍这二大类的配置文件的各类操作。 在config文件中,我将主要演示如何创建自己的自定义的配置节点,而不是介绍如何使用appSetting 。 请明:本文所说的config文件特指app.config或者web.config,而不是一般的XML文件。 在这类配置文件中,由于.net framework已经为它们定义了一些配置节点,因此我们并不能简单地通过序列化的方式去读写它。 config文件 – 自定义配置节点 为什么要自定义的配置节点? 确实,有很多人在使用config文件都是直接使用appSetting的,把所有的配置参数全都塞到那里,这样做虽然不错, 但是如果参数过多,这种做法的缺点也会明显地暴露出来:appSetting中的配置参数项只能按key名来访问,不能支持复杂的层次节点也不支持强类型, 而且由于全都只使用这一个集合,你会发现:完全不相干的参数也要放在一起! 想摆脱这种困扰吗?自定义的配置节点将是解决这个问题的一种可行方法。 首先,我们来看一下如何在app.config或者web.config中增加一个自定义的配置节点。 在这篇博客中,我将介绍4种自定义配置节点的方式,最终的配置文件如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="MySection111" type="RwConfigDemo.MySection1, RwConfigDemo" /> <section name="MySection222" type="RwConfigDemo.MySection2, RwConfigDemo" /> <section name="MySection333" type="RwConfigDemo.MySection3, RwConfigDemo" /> <section name="MySection444" type="RwConfigDemo.MySection4, RwConfigDemo" /> </configSections> <MySection111 username="fish-li" url="http://www.cnblogs.com/fish-li/"></MySection111> <MySection222> <users username="fish" password="liqifeng"></users> </MySection222> <MySection444> <add key="aa" value="11111"></add> <add key="bb" value="22222"></add> <add key="cc" value="33333"></add> </MySection444> <MySection333> <Command1> <![CDATA[ create procedure ChangeProductQuantity( @ProductID int, @Quantity int ) as update Products set Quantity = @Quantity where ProductID = @ProductID; ]]> </Command1> <Command2> <![CDATA[ create procedure DeleteCategory( @CategoryID int ) as delete from Categories where CategoryID = @CategoryID; ]]> </Command2> </MySection333> </configuration> |
同时,我还提供所有的示例代码(文章结尾处可供下载),演示程序的界面如下: config文件 – Property 先来看最简单的自定义节点,每个配置值以属性方式存在:
1 |
<MySection111 username="fish-li" url="http://www.cnblogs.com/fish-li/"></MySection111> |
实现代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class MySection1 : ConfigurationSection { [ConfigurationProperty("username", IsRequired = true)] public string UserName { get { return this["username"].ToString(); } set { this["username"] = value; } } [ConfigurationProperty("url", IsRequired = true)] public string Url { get { return this["url"].ToString(); } set { this["url"] = value; } } } |
小结: 1. 自定义一个类,以ConfigurationSection为基类,各个属性要加上[ConfigurationProperty] ,ConfigurationProperty的构造函数中传入的name字符串将会用于config文件中,表示各参数的属性名称。 2. 属性的值的读写要调用this[],由基类去保存,请不要自行设计Field来保存。 3. 为了能使用配置节点能被解析,需要在<configSections>中注册: <section name="MySection111" type="RwConfigDemo.MySection1, RwConfigDemo" /> ,且要注意name="MySection111"要与<MySection111 ….. >是对应的。 说明:下面将要介绍另三种配置节点,虽然复杂一点,但是一些基础的东西与这个节点是一样的,所以后面我就不再重复说明了。 config文件 – Element 再来看个复杂点的,每个配置项以XML元素的方式存在:
1 2 3 |
<MySection222> <users username="fish" password="liqifeng"></users> </MySection222> |
实现代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class MySection2 : ConfigurationSection { [ConfigurationProperty("users", IsRequired = true)] public MySectionElement Users { get { return (MySectionElement)this["users"]; } } } public class MySectionElement : ConfigurationElement { [ConfigurationProperty("username", IsRequired = true)] public string UserName { get { return this["username"].ToString(); } set { this["username"] = value; } } [ConfigurationProperty("password", IsRequired = true)] public string Password { get { return this["password"].ToString(); } set { this["password"] = value; } } } |
小结: 1. 自定义一个类,以ConfigurationSection为基类,各个属性除了要加上[ConfigurationProperty] 2. 类型也是自定义的,具体的配置属性写在ConfigurationElement的继承类中。 config文件 – CDATA 有时配置参数包含较长的文本,比如:一段SQL脚本,或者一段HTML代码,那么,就需要CDATA节点了。假设要实现一个配置,包含二段SQL脚本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<MySection333> <Command1> <![CDATA[ create procedure ChangeProductQuantity( @ProductID int, @Quantity int ) as update Products set Quantity = @Quantity where ProductID = @ProductID; ]]> </Command1> <Command2> <![CDATA[ create procedure DeleteCategory( @CategoryID int ) as delete from Categories where CategoryID = @CategoryID; ]]> </Command2> </MySection333> |
实现代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
public class MySection3 : ConfigurationSection { [ConfigurationProperty("Command1", IsRequired = true)] public MyTextElement Command1 { get { return (MyTextElement)this["Command1"]; } } [ConfigurationProperty("Command2", IsRequired = true)] public MyTextElement Command2 { get { return (MyTextElement)this["Command2"]; } } } public class MyTextElement : ConfigurationElement { protected override void DeserializeElement(System.Xml.XmlReader reader, bool serializeCollectionKey) { CommandText = reader.ReadElementContentAs(typeof(string), null) as string; } protected override bool SerializeElement(System.Xml.XmlWriter writer, bool serializeCollectionKey) { if( writer != null ) writer.WriteCData(CommandText); return true; } [ConfigurationProperty("data", IsRequired = false)] public string CommandText { get { return this["data"].ToString(); } set { this["data"] = value; } } } |
小结: 1. 在实现上大体可参考MySection2, 2. 每个ConfigurationElement由我们来控制如何读写XML,也就是要重载方法SerializeElement,DeserializeElement config文件 – Collection
1 2 3 4 5 |
<MySection444> <add key="aa" value="11111"></add> <add key="bb" value="22222"></add> <add key="cc" value="33333"></add> </MySection444> |
这种类似的配置方式,在ASP.NET的HttpHandler, HttpModule中太常见了,想不想知道如何实现它们? 代码如下: 小结: 1. 为每个集合中的参数项创建一个从ConfigurationElement继承的派生类,可参考MySection1 2. 为集合创建一个从ConfigurationElementCollection继承的集合类,具体在实现时主要就是调用基类的方法。 3. 在创建ConfigurationSection的继承类时,创建一个表示集合的属性就可以了,注意[ConfigurationProperty]的各参数。 config文件 – […]
View Details在ASP.NET这样的Web应用中,Session是用来保存用户状态的常用手段,不过由于服务器内存空间是有限的,所以Session过期时间设置是很有必要的。在ASP.NET中如何设置Session的过期时间呢,很简单,修改web.config配置。 具体修改方法如下,在web.config中进行如下配置 1 2 3 <system.web> <sessionState mode="InProc" timeout="30"/> </system.web> 在这里指的是Session过期时间为30分钟。也就是说30分钟后如果当前用户没有操作,那么Session就会自动过期了。 from:http://www.cnblogs.com/sjrhero/archive/2010/10/15/1852449.html
View Details