Tips and Tricks


Hopefully if you’re reading this you’ve noticed that I’ve started a series of Tips recently.

The tips will mostly apply to Entity Framework or Data Services.

Seeing as I expect to have a lots of tips, it probably makes sense to have some sort of index.

That is what this is post is, as I add a new tip I will add it to this page too.

If you have any suggested topics for tips please let me know by leaving a comment or emailing me directly at Microsoft (Alexj is my alias at Microsoft, and emails at Microsoft are in the form alias@microsoft.com)

Without further ado here are what I have so far:

Tip 55 – How to extend an IQueryable by wrapping it

Tip 54 – How to improve performance using Statement Expressions

Tip 53 – How to debug EF POCO mapping issues

Tip 52 – How to re-use Types with the Data Services client

Tip 51 – How to load EF metadata from arbitrary streams

Tip 50 – How to query a Data Service using JQuery

Tip 49 – How to find your Data Service bug

Tip 48 – How to host a Data Service in WCF

Tip 47 – How fix-up can make it hard to change relationships

Tip 46 – How to exclude a property using Code-Only

Tip 45 – How to swap EF metadata at runtime

Tip 44 – How to navigate an OData compliant service

Tip 43 – How to authenticate against a Data Service

Tip 42 – How to create a dynamic model using Code-Only

Tip 41 – How to execute T-SQL directly against the database

Tip 40 – How to materialize presentation models via L2E

Tip 39 – How to set overlapping Relationships – EF 4.0 only

Tip 38 – How to use Code Only with Astoria

Tip 37 – How to do a Conditional Include

Tip 36 – How to Construct by Query

Tip 35 – How to write OfTypeOnly<TEntity>()

Tip 34 – How to work with Updatable Views

Tip 33 – How cascade delete really works in EF

Tip 32 – How to create a database from SSDL – EF 4 only

Tip 31 – How to compose L2O and L2E queries

Tip 30 – How to use a custom database function

Tip 29 – How to avoid LazyLoad or Load() reader issues

Tip 28 – How to implement an Eager Loading Strategy

Tip 27 – How to Implement BeforeSave Validation

Tip 26 – How to avoid database queries using Stub Entities

Tip 25 – How to get Entities by key the easy way

Tip 24 – How to get the ObjectContext from an Entity

Tip 23 – How to fake Enums in EF 4

Tip 22 – How to make Include really Include

Tip 21 – How to use the Single() operator – EF 4.0 only

Tip 20 – How to deal with Fixed Length Keys

Tip 19 – How to use Optimistic Concurrency with the Entity Framework

Tip 18 – How to decide on a lifetime for your ObjectContext

Tip 17 – How to do one step updates with AttachAsModified(..)

Tip 16 – How to mimic .NET 4.0’s ObjectSet<T> today

Tip 15 – How to avoid loading unnecessary Properties

Tip 14 – How to cache Entity Framework Reference Data

Tip 13 – How to Attach an Entity the easy way

Tip 12 – How to choose an Inheritance Strategy

Tip 11 – How to avoid Relationship Span

Tip 10 – How to understand Entity Framework jargon

Tip 9 – How to delete an object without retrieving it

Tip 8 – How to write ‘WHERE IN’ style queries using LINQ to Entities

Tip 7 – How to fake Foreign Key Properties in .NET 3.5 SP1

Tip 6 – How and when to use eager loading

Tip 5 – How to restrict the types returned from an EF Query

Tip 4 – Conceptual Schema Definition Language Rules

Tip 3 – How to get started with T4

Tip 2 – Entity Framework Books

Tip 1 – How to sort Relationships in the Entity Framework

Enjoy.

Comments (25)

  1. MSDN Archive says:

    Alex, I have enjoyed perusing through your tips and wanted to request a post on serialization. I recently switched from L2S to EF and now considering switching back because of serialization issues.

    Primarily, when using L2S, I could serialize the returned object as JSON (or XML for that matter) and get simply: { "Id":1, "Name":"John Doe" } but after switching to EF I am stuck with { "Id":1, "Name":"John Doe", "EntityState":"…", "EntityKey":"…", … }

    And the work around to fetch and return objects as Anonymous: (from … where … select new { Id : t.Id, Name : t.Name }).First(); which is obviously undesirable because it means having to specify each field and is quite rigid by design. Any best practices or recommendations?

  2. Alex D James says:

    Aleem,

    Interesting question. I haven’t really thought about this before. I’ll put it on my list of possible posts.

    PS. Looked at your blog, you’ve got a lot of comment spam you should look at tidying up

    Alex

  3. MSDN Archive says:

    Well as it turns out the quick way around it is to return anonymous objects instead of entity objects and use projections.

    > philha@microsofxxxxx wrote:

    > The general approach we recommend is to control the object you’re sending to the browser. Instead of sending the full object you grabbed from the db, you want to perhaps send a projection. For example:

    >

    > Instead of

    >

    >        var product = db.Products.Single(…);

    >        return View(product);

    >

    > You could send an anonymous object with only the fields you want…

    >

    >        var product = db.Products.Single(…);

    >      var jsonProduct = new {Name = product.Name, Price = product.Price};

    >        return View(product);

    Not fond of that approach because it requires extra housekeeping (update projects if db schema or field names change and require explicitly specifying all fields). I’ve fallen back on EFPocoAdapter for now.

    Thanks for pointing out the comment spam. Haven’t used that blog for years. Cleaned up and updated link.

  4. Meta-Me says:

    The Problem: In some of earlier tips we talked about using Attach to load things into the ObjectContext

  5. Alex D James says:

    Aleem,

    I was talking to someone today who talked about a WCF interface called IExtensibleDataObject (http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iextensibledataobject.aspx) that maybe we could use in conjunction with a new T4 template, to hide away EntityKeys etc from the Entity Sent over the wire?

    Anyway just an idea.

    Alex

  6. Meta-Me says:

    This is the 19th post in my ongoing series of Entity Framework Tips . Background: If you have a table

  7. Meta-Me says:

    This is 20th post in my ongoing series of Entity Framework Tips . Fixed Length Field Padding: If you

  8. Meta-Me says:

    This is 21st post in my ongoing series of Entity Framework Tips , and the first that is specific to EF

  9. Meta-Me says:

    As of right now Enums are not in EF4. Now we will be listening to your feedback about Beta1, and making

  10. Entity Framework Tips by Alex James Lately I ran into Alex James blog ( Meta Me ) and into his Entity

  11. VS2010学习 says:

    Sometimes rather than writing this: var customer = ctx.Customers.First(c =&gt; c.ID == 5); You would

  12. VS2010学习 says:

    Customers often ask how to get from an Entity back to the ObjectContext . Now generally we don’t recommend

  13. VS2010学习 says:

    As of right now Enums are not in EF4. Now we will be listening to your feedback about Beta1, and making

  14. VS2010学习 says:

    This is 22nd post in my ongoing series of Entity Framework Tips . If you want to do eager loading with

  15. VS2010学习 says:

    This is 21st post in my ongoing series of Entity Framework Tips , and the first that is specific to EF

  16. VS2010学习 says:

    This is 20th post in my ongoing series of Entity Framework Tips . Fixed Length Field Padding: If you

  17. VS2010学习 says:

    This is the 19th post in my ongoing series of Entity Framework Tips . Background: If you have a table

  18. VS2010学习 says:

    The Problem: In some of earlier tips we talked about using Attach to load things into the ObjectContext

  19. Congrats for this serie of posts Alex, they’re great!

    I’m learing a lot with them, keep up the good work.

    Regards!

  20. Osa says:

    To Aleem question: This is a solution starter. I did not cover navigations because of infinite recursion.

    public static string SerilaizeJSON(this EntityObject entity)

    {

       StringBuilder sb = new StringBuilder(200);

       PropertyInfo[] propertyInfos = entity.GetType().GetProperties();

       Type scalarPropertyType = typeof(EdmScalarPropertyAttribute);

       sb.Append("{"" + entity.GetType().Name + "" : {");

       foreach (PropertyInfo p in propertyInfos) {

           if (p.GetCustomAttributes(scalarPropertyType, false).Count > 0) {

               sb.AppendFormat(""{0}" : "{1}",", p.Name, p.GetValue(entity, null));

           }

       }

       if (propertyInfos.Count > 0) {

           sb.Remove(sb.Length – 1, 1);

       }

       sb.Append("}}");

       return sb.ToString();

    }

  21. Yash says:

    Hi,

    We have a User entity type mapped to a table named tbl_user_profile. This has fields like firstname, lastname, etc. Another entity type Coordinator is mapped to tbl_coordinator. The table has a FK name user_id pointing to the tbl_user_profile table. All coordinators are users but the reverse is not true. The framework we use, expects all fields in the same class and hence, we want all fields of the coordinator in the coordinator entity type. We will not use inheritance because we use RIA domain services which does not support inheritance.

    To achieve this, we added the tbl_user_profile table in the mapping for Coordinator entity type. While doing this we get following error :

    "EntitySets ‘Users’ and ‘Coordinators’ are both mapped to table ‘tbl_user_profile’. Their Primary Keys may collide".

    Error 1 Error 3033: Problem in Mapping Fragment starting at line 2016: EntitySets ‘Users’ and ‘Coordinators’ are both mapped to table ‘tbl_user_profile’. Their Primary Keys may collide.

    E:EDMXEntityModel.edmx  2017    15  MyTrial.Data
    

    "User" has entityset named "Users" and "Coordinator" has entityset named "Coordinators".

    What is the cause and solution to this problem. Any way to work around it?

    Thanks,

    Yash

  22. Blogger says:

    Hi,

    The tip 35 link is broken.

    However google < OfTypeOnly reveals this url which works.

    http://blogs.msdn.com/alexj/archive/2009/09/17/tip-35-how-to-write-oftypeonly-tentity.aspx

    Can you please correct.

  23. Alex D James says:

    @Blogger,

    Thanks for the catch!

    Fixed!

    Cheers

    Alex

  24. robert_d says:

    Nice collection of tips, but it

    lacks one basic example that I couldn't find

    anywhere (OK I didn't google/bing that much ;-)).

    How to save objects in many to many relationship.

    Let's say that there 2 tables Users (for members

    of Library) and ReadBooks.

    Could you give me, please, a code example in c# of:

    1. a User read a book;
    2. a User read a book that was never read before,

    so it isn't stored in ReadBooks table.

    I would greatly appreciate your answer,

    Robert