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 元素

参阅

C#反转链表

public class ReverseLinkedList
    {
        void main()
        {
            Node list = InitList();
            Console.WriteLine(list);
            list = list.ReverseList(list);
            Console.WriteLine(list);
        }
        public Node InitList()
        {
            Node head = new Node();
            head.Next = null;
            head.Data = -1;
            Node q, p;
            p = head;
            for (int i = 1; i <= 10; i++)
            {
                q = new Node();
                q.Data = i;
                q.Next = null;
                p.Next = q;
                p = q;
            }
            return head;
        }
    }
    public class Node
    {
        private T data;
        private Node next;
        public T Data
        {
            get { return data; }
            set { this.data = value; }
        }
        public Node Next
        {
            get { return next; }
            set { next = value; }
        }
        public Node ReverseList(Node head)
        {
            if (head.Next == null || head.Next.Next == null)
            {
                return head;   /*链表为空或只有一个元素则直接返回*/
            }
            Node t = null,
                     p = head.Next,
                     q = head.Next.Next;
            while (q != null)
            {
                t = q.Next;
                q.Next = p;
                p = q;
                q = t;
            }
            /*此时q指向原始链表最后一个元素,也是逆转后的链表的表头元素*/
            head.Next.Next = null;  /*设置链表尾*/
            head.Next = p;           /*调整链表头*/
            return head;
        }
        public override string ToString()
        {
            string result = string.Empty ;
            Node p = this.Next;
            while (p != null)
            {
                result += string.Format("{0}t", p.Data);
                p = p.Next;
            }
            return result;
        }
    }

怎么样才是好的程序员(转)

要判断一个程序员是不是好的程序员,主要看他写的代码,因为程序员最重要的事是写代码。
即便不去理解代码的意图,只要看一眼,好的程序员写的代码与差的程序员写的代码基本上就可以看出来。好的程序员写的代码,整洁而规范,视觉上自然有一种美感。空白错落有致,注释恰到好处,命名和排版遵守统一的规范。差的程序员写的代码则经常出现过长的函数,前后不一致的命名方式和排版,过深的嵌套结构,非常复杂的表达式,随处可见的数字等毛病。
再去粗粗阅读,对好的程序员还是差的程序员就会更有把握。好的程序员写的代码,有一种精心雕琢而成的一致性。好的程序员一致会遵守统一的命名方式,如camelCase,而差的程序员的变量命名时不时的就会偏离统一规范。好的程序员的代码中拼写错误几乎不可见,而差的程序员的拼写错误要多得多。好的程序员对于同一类动作,不会忽而用这个动词,忽而又用那个同义词,如add/insert混用。好的程序员采用一致的简写规则,差的程序员则时而不简写,时而简写。好的程序员会很注意名称中形容词与名词谁在前谁在后,而差的程序员没有规则,时而在前时而在后。好的程序员很少会写出大段大段的重复代码,差的程序员却经常搞不定重复代码,他们难以将重复的代码抽取出一个统一的概念进行重用。好的程序员对于对外的API会注重注释与代码的一致性,差的程序员经常注释中的参数名称与函数定义都不一致。好的程序员很少会留下被注释掉的或用#if 0括起的垃圾代码,他们意志坚决,代码有用就要,没用就不要,差的程序员则不一样,他们经常不确信一段代码是否真的需要,他们缺乏保持代码整洁的习惯,因此他们让垃圾代码留着。
如上,即便你不懂他所用的语言,不却关心程序的逻辑,对好的程序员还是差的程序员就能做到八九不离十的判断。程序的好坏几乎总是取决于它们是否“漂亮”,不“漂亮”而好的程序,除了C++ STL源码,我再也没见过(如果你稍仔细看,STL的源码虽然不够“漂亮”,但仍然满足这里提出的一致性原则)。而又好又“漂亮”的代码则随处可见,如Linux Kernel,InnoDB,JDK,JUnit等等。
如果再仔细阅读,就能更准确。好的程序员写的代码,好似浑然天成,简单而直白。函数通常较短小,函数的名称准确的反映函数要完成的工作。逻辑简单而自然,让你读的时候由衷的发出“啊,就应该是这样”的感叹,而差的程序员的代码经常让你发出“怎么是这样?这是再干什么呀?”的疑问。好的程序员会在紧要关头加以画龙点睛般的注释,差的程序员要么没注释,要么注释只是代码的重复,纯粹是废话,更差的是注释是错的,是误导。
好的程序员未必是“语言律师”,即那种非常清楚的了解语言的各个细节,在编程时到处使用的家伙。好的程序员也不常“炫技”,在代码中精心构造一些独具匠心的片断,他们偶而会,但大多数时候总是用直白的语言来表述。
从代码也可以看出一个程序员的团队协作精神。注意团队合作的程序员,会严格按照团队规范写代码,而风格与团队规范不一致的程序员则很可能欠缺团队精神。注意团队合作的程序员会注意给模块的对外接口加以重要的说明,如前置条件、后置条件、参数能否是NULL等等,不注意团队合作的程序员懒于处理这些细节。
好的程序员与差的程序员的生产力差别巨大,项目的周期越长,项目越复杂,项目对质量的要求越高,好的程序员的价值就越大。好的程序员与差的程序员,管理成本也差别巨大,好的程序员只需要与他共同确定设计,代码可以不看,差的程序员的代码经常需要经过多次review,且仍有可能达不到理想的质量。
要成为好的程序员,首先要树立要成为好的程序员的志向,再勤加练习,天长日久,就会越来越好,这些人不怕老。没有志向永远成不了好的程序员,这些人若不在老去之前成为经理就会变成废人。
通过两个小时的笔试和半个小时的面试对于判断程序员来说是不够的。通过笔试与面试,你可以判断一个程序员是否具备算法与数据结构等基础知识,可以判断他对编程语言的特性是否掌握,可以判断他对技术是否关注,然而要知道他能否真的能很好的完成工作,不写代码是不够的。
那些显得对技术充满热情的,未必是好的程序员。这些人可能非常乐意从事有新意的工作,但后续的编码、测试、调试、文案工作则可能让他们感到厌烦。他们可能会提出好的创意,但却经常不能够有始有终的将其完成。公司不需要多少这样的人。
因此招聘的方式需要改善。招聘是最重要的,因为进来后就难以出去,即便是试用。转正条件白纸黑字写的很清楚,只要合格就可以转正,要达到合格并不是很困难。今年部门里进了很多新人,并不是人人都很优秀,但确实也都合格,自然也应该转正。
改善招聘的方法,就是让他写程序,可以出两道题,一道让他写程序,一道让他重构一个已有的较长的程序,一天之内完成。假使可以考他半个月,那么重构是不太需要的,但一天的时间太短,通过重构可以考察阅读并理解代码,并通过重构“化腐朽为神奇”的能力。那些不愿意写别人的代码,不愿意接受别人的代码,经常要重来一遍的人是不理想的。
今年有两个人采用了类似的方法。有一位简历很优秀的人,做了两道编程题被拒了,有一位简历及面试一般的人,通过编程测试,录用了。我感觉比单纯的笔试与面试要准确。