Linq “Could not translate expression… into SQL and could not treat it as a local expression.”

You could use AsEnumerable on the entity, but that would force it to bring back all the columns (even if not used); perhaps instead something like: var q1 = from ent in LinqUtils.GetTable<Entity>() from tel in ent.Telephones.DefaultIfEmpty() select new { Name = ent.FormattedName, Number = (tel == null ? null : ent.Number), Extension = (tel … Read more

T4 template to Generate Enums

I have written one for my needs that converts a lookup table of your choice to an enum: Put this code inside an EnumGenerator.ttinclude file: <#@ template debug=”true” hostSpecific=”true” #> <#@ output extension=”.generated.cs” #> <#@ Assembly Name=”System.Data” #> <#@ import namespace=”System.Data” #> <#@ import namespace=”System.Data.SqlClient” #> <#@ import namespace=”System.IO” #> <#@ import namespace=”System.Text.RegularExpressions” #> <# … Read more

How can I add my attributes to Code-Generated Linq2Sql classes properties?

You can take advantage of the new Metadata functionality in the System.ComponentModel.DataAnnotations which will allow us to separate the MetaData from the existing domain model. For example: [MetadataType (typeof (BookingMetadata))] public partial class Booking { // This is your custom partial class } public class BookingMetadata { [Required] [StringLength(15)] public object ClientName { get; set; … Read more

Multiple/single instance of Linq to SQL DataContext

Rick Strahl has a nice article about your options: http://www.west-wind.com/weblog/posts/246222.aspx. See also: LINQ to SQL – where does your DataContext live?. You may want a slightly different strategy for each type of deployment – web, desktop, windows service… Summarized, your options are: Global DataContext – dangerous in multi-threaded environments (including web apps). Remember that instance … Read more

List, IList, IEnumerable, IQueryable, ICollection, which is most flexible return type?

Collections are not generally very useful for DAL returns, because a collection does not implicitly guarantee order. It’s just a bucket of items. An IList, on the other hand, does implicitly guarantee order. So we’re down to IEnumerable or IList. The next question would be: is the List object “live”? i.e., is it connected to … Read more