月度归档:2013年07月

Entity Framework Loading Related Entities

Entity Framework supports three ways to load related data – eager loading, lazy loading and explicit loading. The techniques shown in this topic apply equally to models created with Code First and the EF Designer.
 

Eagerly Loading

Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved by use of the Include method. For example, the queries below will load blogs and all the posts related to each blog.

using (var context = new BloggingContext())
{
  // Load all blogs and related posts
  var blogs1 = context.Blogs
                .Include(b => b.Posts)
                .ToList();
  // Load one blogs and its related posts
  var blog1 = context.Blogs
                .Where(b => b.Name == “ADO.NET Blog”)
                .Include(b => b.Posts)
                .FirstOrDefault();
  // Load all blogs and related posts
  // using a string to specify the relationship
  var blogs2 = context.Blogs
                .Include(“Posts”)
                .ToList();
  // Load one blog and its related posts
  // using a string to specify the relationship
  var blog2 = context.Blogs
                .Where(b => b.Name == “ADO.NET Blog”)
                .Include(“Posts”)
                .FirstOrDefault();
}
Note that Include is an extension method in the System.Data.Entity namespace so make sure you are using that namespace.

Eagerly loading multiple levels

It is also possible to eagerly load multiple levels of related entities. The queries below show examples of how to do this for both collection and reference navigation properties.

using (var context = new BloggingContext())
{
  // Load all blogs, all related posts, and all related comments
  var blogs1 = context.Blogs
                 .Include(b => b.Posts.Select(p => p.Comments))
                 .ToList();
  // Load all users their related profiles, and related avatar
  var users1 = context.Users
                .Include(u => u.Profile.Avatar)
                .ToList();
  // Load all blogs, all related posts, and all related comments
  // using a string to specify the relationships
  var blogs2 = context.Blogs
                 .Include(“Posts.Comments”)
                 .ToList();
  // Load all users their related profiles, and related avatar
  // using a string to specify the relationships
  var users2 = context.Users
                .Include(“Profile.Avatar”)
                .ToList();
}
Note that it is not currently possible to filter which related entities are loaded. Include will always being in all related entities.
 

Lazy Loading

Lazy loading is the process whereby an entity or collection of entities is automatically loaded from the database the first time that a property referring to the entity/entities is accessed. When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook. For example, when using the Blog entity class defined below, the related Posts will be loaded the first time the Posts navigation property is accessed:

public class Blog
{
  public int BlogId { get; set; }
  public string Name { get; set; }
  public string Url { get; set; }
  public string Tags { get; set; }
  public virtual ICollection Posts { get; set; }
}

Turning off lazy loading for specific navigation properties

Lazy loading of the Posts collection can be turned off by making the Posts property non-virtual:

public class Blog
{
  public int BlogId { get; set; }
  public string Name { get; set; }
  public string Url { get; set; }
  public string Tags { get; set; }
  public ICollection Posts { get; set; }
}
Loading of the Posts collection can still be achieved using eager loading (see?Eagerly loading related entities?above) or the Load method (see?Explicitly loading related entities?below).

Turn off lazy loading for all entities

Lazy loading can be turned off for all entities in the context by setting a flag on the Configuration property. For example:

public class BloggingContext : DbContext
{
    public BloggingContext()
    {
        this.Configuration.LazyLoadingEnabled = false;
    }
}
Loading of related entities can still be achieved using eager loading (see?Eagerly loading related entities?above) or the Load method (see?Explicitly loading related entities?below).
 

Explicitly Loading

Even with lazy loading disabled it is still possible to lazily load related entities, but it must be done with an explicit call. To do so you use the Load method on the related entity’s entry. For example:

using (var context = new BloggingContext())
{
  var post = context.Posts.Find(2);
  // Load the blog related to a given post
  context.Entry(post).Reference(p => p.Blog).Load();
  // Load the blog related to a given post using a string
  context.Entry(post).Reference(“Blog”).Load();
  var blog = context.Blogs.Find(1);
  // Load the posts related to a given blog
  context.Entry(blog).Collection(p => p.Posts).Load();
  // Load the posts related to a given blog
  // using a string to specify the relationship
  context.Entry(blog).Collection(“Posts”).Load();
}
Note that the Reference method should be used when an entity has a navigation property to another single entity. On the other hand, the Collection method should be used when an entity has a navigation property to a collection of other entities.

Applying filters when explicitly loading related entities

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities. You can then use LINQ to apply filters to the query before executing it with a call to a LINQ extension method such as ToList, Load, etc. The Query method can be used with both reference and collection navigation properties but is most useful for collections where it can be used to load only part of the collection. For example:

using (var context = new BloggingContext())
{
    var blog = context.Blogs.Find(1);
    // Load the posts with the ‘entity-framework’ tag related to a given blog
    context.Entry(blog)
        .Collection(b => b.Posts)
        .Query()
        .Where(p => p.Tags.Contains(“entity-framework”)
        .Load();
    // Load the posts with the ‘entity-framework’ tag related to a given blog
    // using a string to specify the relationship
    context.Entry(blog)
        .Collection(“Posts”)
        .Query()
        .Where(p => p.Tags.Contains(“entity-framework”)
        .Load();
}
When using the Query method it is usually best to turn off lazy loading for the navigation property. This is because otherwise the entire collection may get loaded automatically by the lazy loading mechanism either before or after the filtered query has been executed.
Note that while the relationship can be specified as a string instead of a lambda expression, the returned IQueryable is not generic when a string is used and so the Cast method is usually needed before anything useful can be done with it.
 

Using Query to count related entities without loading them

Sometimes it is useful to know how many entities are related to another entity in the database without actually incurring the cost of loading all those entities. The Query method with the LINQ Count method can be used to do this. For example:

using (var context = new BloggingContext())
{
    var blog = context.Blogs.Find(1);
    // Count how many posts the blog has
    var postCount = context.Entry(blog)
                          .Collection(b => b.Posts)
                          .Query()
                          .Count();
}

ActionResults action returns

Name Framework Behavior Producing Method
ContentResult Returns a string literal Content
EmptyResult No response
FileContentResult
FilePathResult
FileStreamResult
Return the contents of a file File
HttpUnauthorizedResult Returns an HTTP 403 status
JavaScriptResult Returns a script to execute JavaScript
JsonResult Returns a data in JSON format Json
RedirectResult Redirects the client to a new URL Redirect
RedirectToRouteResult Redirect to another action, or
another controller’s action
RedirectToRoute
RedirectToAction
ViewResult
PartialViewResult
Response is the responsibility
of a view engine
View/PartialView

关于CSS优先级的详细解说

在讲CSS优先级之前,我们得要了解什么是CSS,CSS是用来做什么的。简单说来,CSS是层叠样式表(Cascading Style Sheets)的简称。它的规范代表了互联网历史上一个独特的发展阶段。现在对于从事网页制作的朋友来说,应该很少没有听说过CSS了,因为在制作网页过程中我们经常需要用到。我们能通过CSS为文档设置丰富且易于修改的外观,以减轻网页制作者的工作负担,从而减轻制作及后期维护的代价。
其实现在还来讲CSS是什么,CSS有什么作用完全是多余的,相信从事网页制作的朋友都已经或多或少的接触过了。言归正传,开始进入今天的话题。
一、什么是CSS优先级?
所谓CSS优先级,即是指CSS样式在浏览器中被解析的先后顺序。
二、CSS优先级规则
既然样式有优先级,那么就会有一个规则来约定这个优先级,而这个“规则”就是本次所需要讲的重点。
样式表中的特殊性描述了不同规则的相对权重,它的基本规则是:
1、统计选择符中的ID属性个数。
2、统计选择符中的CLASS属性个数。
3、统计选择符中的HTML标记名个数。
最后,按正确的顺序写出三个数字,不要加空格或逗号,得到一个三位数(css2.1是用4位数表示)。( 注意,你需要把数字转换成一个以三个数字结尾的更大的数)。相应于选择符的最终数字列表可以很容易确定较高数字特性凌驾于较低数字的。
例如:
1、每个ID选择符(#someid),加 0,1,0,0。
2、每个class选择符(.someclass)、每个属性选择符(形如[attr=value]等)、每个伪类(形如:hover等)加0,0,1,0。
3、每个元素或伪元素(:firstchild)等,加0,0,0,1。
4、其它选择符包括全局选择符*,加0,0,0,0。相当于没加,不过这也是一种specificity,后面会解释。
三、特性分类的选择符列表
以下是一个按特性分类的选择符的列表:

单从上面这个表来看,貌似不大好理解,下面再给出一张表:

通过上面,就可以很简单的看出,HTML标记的权重是1,CLASS的权重是10,ID的权重是100,继承的权重为0(后面会讲到)。
按这些规则将数字符串逐位相加,就得到最终的权重,然后在比较取舍时按照从左到右的顺序逐位比较。
优先级问题其实就是一个冲突解决的问题,当同一个元素(内容)被CSS选择符选中时,就要按照优先级取舍不同的CSS规则,这其中涉及到的问题其实很多。
说到这里,我们不得不说一下CSS的继承性

四、CSS的继承性

 4.1 继承的表现

继承是CSS的一个主要特征,它是依赖于祖先-后代的关系的。继承是一种机制,它允许样式不仅可以应用于某个特定的元素,还可以应用于它的后代。例如一个BODY定义了的颜色值也会应用到段落的文本中。

样式定义:

举例代码:

  1

举例效果:

这段代码的应用结果是:“CSS继承性的测试”这段话是红颜色的,“继承性”几个字由于应用了标签,所以是粗体。很显然,这段文字都继承了由body {color:#f00;}样式定义的颜色。这也就是为什么说继承性是CSS的一部分。

然而CSS继承性的权重是非常低的,是比普通元素的权重还要低的0。

我们仍以上面的举例代码为例:在样式定义中添加一条:

1

举例效果:

发现只需要给加个颜色值就能覆盖掉它继承自的样式颜色。由此可见:任何显示申明的规则都可以覆盖其继承样式。

4.2 继承的局限性

继承是CSS重要的一部分,我们甚至不用去考虑它为什么能够这样,但CSS继承也是有限制的。

有一些属性不能被继承,如:border, margin, padding,?background等。

样式定义:

1

举例代码:

1

预期效果:

实际效果:

从上面的效果中,我们可以看出,border是不能被继承的,还有一些其它的属性也是如此,这里就不一一列举。

五、附加说明

1、文内的样式优先级为1,0,0,0,所以始终高于外部定义。这里文内样式指形如<div style=”color:red>blah</div>的样式,而外部定义指经由<link>或<style>卷标定义的规则。

2、有!important声明的规则高于一切。

3、如果!important声明冲突,则比较优先权。

4、如果优先权一样,则按照在源码中出现的顺序决定,后来者居上。

5、由继承而得到的样式没有specificity的计算,它低于一切其它规则(比如全局选择符*定义的规则)。

6、关于经由@import加载的外部样式,由于@import必须出现在所有其它规则定义之前(如不是,则浏览器应该忽略之),所以按照后来居上原则,一般优先权冲突时是占下风的。

还需要说一下,IE是可以识别位置错误的@import的,但无论@import在什么地方,它都认为是位于所有其它规则定义之前的,这可能会引发一些误会。

优先权问题看起来简单,但背后还是有非常复杂的机制,在实际应用中需要多多留意。

C#二叉树

public class TreeNode
    {
        private T data;
        private TreeNode leftNode;
        private TreeNode rightNode;
        public TreeNode(T nodeValue)
        {
            data = nodeValue;
            leftNode = null;
            rightNode = null;
        }
        //数据
        public T Data
        {
            get { return data; }
            set { data = value; }
        }
        //左子树
        public TreeNode LeftNode
        {
            get { return leftNode; }
            set { leftNode = value; }
        }
        //右子树
        public TreeNode RightNode
        {
            get { return rightNode; }
            set { rightNode = value; }
        }
        /// 
        /// 前序遍历:先跟节点然后左子树,右子树
        /// 
        /// 
        public void PreOrderTree(TreeNode root)
        {
            if (root != null)
            {
                Console.Write(root.Data);
                PreOrderTree(root.LeftNode);
                PreOrderTree(root.RightNode);
            }
        }
        /// 
        /// 中序遍历:左子树,根节点,右子树可以实现顺序输出
        /// 
        /// 
        public void InOrderTree(TreeNode root)
        {
            if (root != null)
            {
                InOrderTree(root.LeftNode);
                Console.Write(root.Data);
                InOrderTree(root.RightNode);
            }
        }
        /// 
        /// 深度
        /// 
        /// 
        /// 
        public int GetTreeDepth(TreeNode tree)
        {
            if (tree == null)
                return 0;
            int leftDepth = GetTreeDepth(tree.LeftNode);
            int rightDepth = GetTreeDepth(tree.RightNode);
            return leftDepth > rightDepth ? (leftDepth + 1) : (rightDepth + 1);
        }
    }

jQuery 选择器

jQuery 选择器

选择器 实例 选取
* $(“*”) 所有元素
#id $(“#lastname”) id=”lastname” 的元素
.class $(“.intro”) 所有?class=”intro”?的元素
element $(“p”) 所有 <p> 元素
.class.class $(“.intro.demo”) 所有 ?class=”intro” 且?的元素
:first $(“p:first”) 第一个 <p> 元素
:last $(“p:last”) 最后一个 <p> 元素
:even $(“tr:even”) 所有偶数 <tr> 元素
:odd $(“tr:odd”) 所有奇数 <tr> 元素
:eq(index) $(“ul li:eq(3)”) 列表中的第四个元素(index 从 0 开始)
:gt(no) $(“ul li:gt(3)”) 列出 index 大于 3 的元素
:lt(no) $(“ul li:lt(3)”) 列出 index 小于 3 的元素
:not(selector) $(“input:not(:empty)”) 所有不为空的 input 元素
:header $(“:header”) 所有标题元素 <h1> – <h6>
:animated 所有动画元素
:contains(text) $(“:contains(‘W3School’)”) 包含指定字符串的所有元素
:empty $(“:empty”) 无子(元素)节点的所有元素
:hidden $(“p:hidden”) 所有隐藏的 <p> 元素
:visible $(“table:visible”) 所有可见的表格
s1,s2,s3 $(“th,td,.intro”) 所有带有匹配选择的元素
[attribute] $(“[href]”) 所有带有 href 属性的元素
[attribute=value] $(“[href=’#’]”) 所有 href 属性的值等于 “#” 的元素
[attribute!=value] $(“[href!=’#’]”) 所有 href 属性的值不等于 “#” 的元素
[attribute$=value] $(“[href$=’.jpg’]”) 所有 href 属性的值包含以 “.jpg” 结尾的元素
:input $(“:input”) 所有 <input> 元素
:text $(“:text”) 所有 type=”text” 的 <input> 元素
:password $(“:password”) 所有 type=”password” 的 <input> 元素
:radio $(“:radio”) 所有 type=”radio” 的 <input> 元素
:checkbox $(“:checkbox”) 所有 type=”checkbox” 的 <input> 元素
:submit $(“:submit”) 所有 type=”submit” 的 <input> 元素
:reset $(“:reset”) 所有 type=”reset” 的 <input> 元素
:button $(“:button”) 所有 type=”button” 的 <input> 元素
:image $(“:image”) 所有 type=”image” 的 <input> 元素
:file $(“:file”) 所有 type=”file” 的 <input> 元素
:enabled $(“:enabled”) 所有激活的 input 元素
:disabled $(“:disabled”) 所有禁用的 input 元素
:selected $(“:selected”) 所有被选取的 input 元素
:checked $(“:checked”) 所有被选中的 input 元素

参阅