Query syntax: var count = (from t in context.MyTable where t.Id == @Id select t).Count(); Method syntax: var count = context.MyTable .Where(t => t.Id == @Id) .Count() Both generate the same SQL query.
Tag: entity
What is the difference between Select and SelectMany in Linq
The formal description for SelectMany() is: Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence. SelectMany() flattens the resulting sequences into one sequence and invokes a result selector function on each element. The main difference is the result of each method while SelectMany() returns flattened results; Select() […]
Differences between FirstOrDefault and SingleOrDefault in LINQ
Whenever you use SingleOrDefault, you clearly state that the query should result in at most a single result. On the other hand, when FirstOrDefault is used, the query can return any amount of results but you state that you only want the first one. If your result set returns 0 records: Single throws an exception First throws an exception SingleOrDefault returns the default […]
What is the difference between IQueryable and IEnumerable?
That StackOverflow answer so far is the best one I have ever seen: This is an excellent video on youtube which demonstrates how these interfaces differ, worth a watch. Below goes a long descriptive answer to it. The first important point to remember is IQueryable interface inherits from IEnumerable, so whatever IEnumerable can do, IQueryable can also do. There are many differences […]
How to add default value for Entity Framework migrations for DateTime and Bool
Just add defaultValue parameter in CreateTable method for property: public partial class TestSimpleEntity : DbMigration { public override void Up() { CreateTable( “dbo.SimpleEntities”, c => new { id = c.Long(nullable: false, identity: true), name = c.String(), deleted = c.Boolean(nullable: false, defaultValue: true), }) .PrimaryKey(t => t.id); } public override void Down() { DropTable(“dbo.SimpleEntities”); } } After that, run update-database -verbose command, […]