pátek 21. března 2014

EF: intColumn.ToString() doesn't work in LINQ to Entities, SqlFunctions.StringConvert outside


As you may already know LINQ to Entities will not let you do something like
  "Blah blah blah " + t.charColumn + " (" + t.intColumn.ToString() + ")"
in a query. What quite a few do not know is that you can instead use 
  "Blah blah blah " + t.charColumn + " (" + System.Data.Objects.SqlClient.SqlFunctions.StringConvert(t.intColumn) + ")"

there is a catch though ... this will ONLY work inside a query! So if you happen to have an entity already, you can't use this ... it would probably be too hard to implement, much harder than throwing an exception ...

Why do I care? Generated code. Suppose you have quite a few lookup tables (countries, types of this, types of that, regions, ... anything really) and you need to populate the pulldowns. Sometimes it's enough to display one property, sometimes you want to do something a bit more complicated ... like include the ID in the displayed text. To simplify things for the developers you extend the EF designer so that they could specify that an entity may be turned into a dropdown and what's the property/expression to display. And the tweaked .tt file generates the interface implementation and the extension methods that turn an IQueryable of entities to an IEnumerable<SelectListItems> etc. etc. etc. With the extension methods written so that we do not fetch the whole entities, but rather Select() just what we need. 
And here comes the catch of course. The same code to compute the text to display is used in
 query.Select(e => new {Value = e.Id, Text = HERE}).AsEnumerable().Select(s => new SelectListItem{Id = s.Id, Text = s.Text})
and in
 string IListItem.Text { { get { return HERE } }
where the later is used when I already have an entity and need to display the text as in the drop down.
And seems if I need to include the ID in the text there is no solution that'd work both in LINQ to Entities and outside.
Or am I wrong?

Yes, I am wrong. There is a solution. The same one I used to allow me to use LIKE in LINQ to Entities queries. 

If I add this into the .edmx into <edmx:Runtime><edmx:ConceptualModels><Schema> :
<Function Name="Int32_SqlToString" ReturnType="Edm.String" ef4ex:RenameTo="SqlToString">
  <Parameter Name="val" Type="Edm.Int32" />
  <DefiningExpression>
   Cast(val as Edm.String)
  </DefiningExpression>
  <ef4ex:CodeBlock>
   return val.ToString();
  </ef4ex:CodeBlock>
 </Function>

and 
[System.Data.Objects.DataClasses.EdmFunction( "Xxxx.Models", "Int32_SqlToString")]
 public static String SqlToString(this Int32 val) {
  return val.ToString();
 }

into a static class (it's actually generated using the data from the ef4ex tags and attributes), then I can use
 intColumn.SqlToString()
anywhere.
The only problem is that in a project where I'd need two different models based on two .edmx files I'd have to define the function twice and then could only import one or the other namespace and there's be nothing preventing me from using the wrong .SqlToString() triggering a run time error.

To solve that I would have to be allowed to put several [System.Data.Objects.DataClasses.EdmFunction()] attributes to one extension method and the LINQ to Entities would have to select the right EntitySQL implementation based on the namespaceName.
It's a shame there is (as far as I know) no way to attach the EdmFunction mapping to a method written by someone else in a way the LINQ to Entities provider would understand and thus give it a hint how to convert the method into the SQL :-(

C# 6.0 - constant parameters and partial evaluation

If you work with things like ASP.Net MVC things like

Html.EditorFor(m => m.Name)

look familiar. There is a fairly big problem with this code. It works all right, but it's inefficient. The point is that it keeps on redoing the same thing again and again and again. Find out what property of what type the lambda points to, read the attributes via reflection, find the right editor template, fill in the values of those attributes ... all these things are done over and over and over again. Even though the lambda is constant, the attributes assigned to the property are constant, the templates are constant ... the only thing important for this that changes is the value of the model hidden in the HtmlHelper.

You can cache the attributes and some other stuff, but it's still not as efficient as it could be.

What would be nice would be to be able to split the contents of the EditorFor() method into the stuff that depends only on the constant parameter (the Expression) and the stuff that depends on the current value of the Model and ViewState. To make things easier let's make a much simpler example. Suppose we have a method like this:

public static float Foo(float x, float y) {
  return Math.sqrt(x) + Math.Sqrt(y);
}


Now, Math.Sqrt() is not a particularly expensive method, but suppose whatever we do with the parameter x is expensive and we have lots of calls like this

var result = Our.Foo( 5.7, y)

so we would like to do the computation that only depends on x once. We we would add one more overload of the Foo() method like this:

public 
static float Foo(const float x, float y) {
  var sqrt_x = Math.Sqrt(x);
  return (y) => sqrt_x + Math.Sqrt(y);
}


which would get compiled as

public Func<float,float> Foo_const_x(float x) {
  var sqrt_x = Math.Sqrt(x);
  return (y) => sqrt_x + Math.Sqrt(y);
}


And then the call above would get compiled as

if (_generated_static_for_const_163 == null)

   _generated_static_for_const_163 = Foo_const_x(5.7);
var result = 
_generated_static_for_const_163(y)
...
private static Func<float,float>
_generated_static_for_const_163;


Caching in current C#

I know that in some cases caching inside the method would work:

private static ConcurrentDictionary<float,float> _cacheFooX = new ConcurrentDictionary
<float,float>();
public static float Foo(float x, float y) {
  var sqrt_x = _cacheFooX.GetOrAdd(x, xx => Math.Sqrt(xx));
  return sqrt_x + Math.Sqrt(y);
}


but there are several problems with this solution.

  1. It's kinda wordy. 
  2. Not all objects may be used as a hash key either at all or with reasonable performance. 
  3. This way you cache all values of "x" the method is ever called with, not just the constants. Sometimes it's OK, sometimes it'd cause huge memory footprint with no speed gain. It makes sense to cache Our.Foo( 4.7, y), especially if it's inside an often called method. It doesn't make sense to cache for (var x = 0; x < 100; x += 0.002) { var r = Our.Foo(x, 78); ...
  4. If the thing you'd like to do just once is not to compute some value, but rather to decide which of the twenty possible actions you want to do with the rest of the parameters, the caching doesn't work so well.
An example of the thing that would work well with the const proposal and not so well with the cache could go something like this:

public static MvcHtmlString Input<TModel,TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel,TValue>> expr) {
  var info = new InfoAboutProperty(expr); // lots of use of reflection etc.
  if (info.AllowsMultipleValues) {
   if (info.RenderAs == RenderAs.Multiselect) {
    do whatever it takes to render the select multiple, get the options based on the attributes, etc.
    return theGeneratedHtml;
   } else if (info.RenderAs == RenderAs.Checkboxes) {

    do whatever it takes to render the intput type="checkbox"es, get the options based on the attributes, etc.
    return theGeneratedHtml;
   } else ...

With the const it's simply

public static MvcHtmlStrig Input<TModel,TValue>(this HtmlHelper<TModel> html, const Expression<Func<TModel,TValue>> expr) {
  var info = new InfoAboutProperty(expr); // lots of use of reflection etc.
  if (info.AllowsMultipleValues) {
   if (info.RenderAs == RenderAs.Multiselect) {
    return html => {
     do whatever it takes to render the select multiple, get the options based on the attributes, etc.
     return theGeneratedHtml;
    };
   } else if (info.RenderAs == RenderAs.Checkboxes) {
    return html => {
     do whatever it takes to render the intput type="checkbox"es, get the options based on the attributes, etc.
     return theGeneratedHtml;
    };

   } else ...

Generic methods

In the case of generic methods sometimes a lot of work can be done just knowing the type so it would be great if the const modifier could be applied even to the type parameters:

public static something Foo<const T>(T x) {
  do some reflection or something using the type T
  return x => { ...};
}

Implementation could be exactly the same.

Of course for this to really be of use, expressions and lambdas with no enclosed variable would have to be considered constants :-)

čtvrtek 4. července 2013

Search and destroy!

This

in case you would not know is the search ... erm ... thing ... in Visual Studio 2012. I would not call that dialog, something so outdated could not be used in the new, carefully designed, incredible, ubercool and megalovely formerly-known-as-Metro-but-the-Metro-company-rightfully-complained style. So let's call that a "thing". Now quick! is the search gonna be case sensitive or case insensitive? Is it gonna be whole word only or not? Is it gonna use "regular expressions" or not (I wonder do they still use their own braindead something that kinda resembles incorrectly understood and mostly forgotten regexps or actual ones)?


Dear designer, it's commendable that you try to save space. You did a very bad job on this "thing" though. The whole team that designed the new version of Visual Studio should be fired and never ever let anywhere near computers again! Ever!


I pity all those that worked hard on the additions to the language, improvements of the compiler and tools that their work is hidden under the heap of crap that is the new UI!

úterý 6. března 2012

blah.blih(bla,bla,bla).Whatever.Substring(0,6) kabooom

Yes you are right, this is yet another of the "someone's stupid" posts. Is there anyone, anyone at all, who thinks it's a good idea to throw an ArgumentOutOfRangeException("Index and length must refer to a location within the string.") if the second parameter to Substring() is too big? For gawds sake when was there a time you cared? I want the bloody result to be at most 6 fscking characters! I don't give a flying fsck if it's four already! No body gives a flying fuck! It might make sense to throw when the index points outside the string even though a more sensible approach would be to stay calm and return an empty string, but throwing just because there's not enough silly characters is simply ... microsoftish.

čtvrtek 4. srpna 2011

enumerable.Distinct(IEqualityComparer what???

Now I understand years ago when there were no lambdas in C# and the syntax for function references (delegates for the C# folk) was so convoluted that they were almost unusable ... at those dark times all those IEqualityComparers and loads of other interfaces made some sense but now? All I want is to filter some enumerable to get only the distinct values where distinct means the .ArticleId property is different (other properties either depend on ArticleId or are irrelevant and will not be used when processing the filtered list). Should be simple right? I expected something like var filtered = list.Distinct( (obj1, obj2) => obj1.ArticleId == obj2.ArticleId ); or even (as the ArticleId is a plain old int) var filtered = list.Distinct( obj => obj.ArticleId ); Too simple. ... private class DogsWithTheSameArticle : IEqualityComparer<WatchDogsToSend> { public bool Equals(WatchDogsToSend dog1, WatchDogsToSend dog2) { return dog1.ArticleId == dog2.ArticleId; } public int GetHashCode(WatchDogsToSend dog) { return dog.GetHashCode(); } } ... ... many a line away ... ... var filtered = notification.Distinct((IEqualityComparer<WatchDogsToSend>)(new DogsWithTheSameArticle())); OK. It works. But it's long and ugly, ugly, ugly. Let us hide the insanity! private class LambdaEqualityComparer<T> : IEqualityComparer<T> { private Func<T, T, bool> _comparer; public LambdaEqualityComparer(Func<T, T, bool> comparer) { _comparer = comparer; } public bool Equals(T obj1, T obj2) { return _comparer(obj1, obj2); } public int GetHashCode(T obj) { return 0; } } private class LambdaEqualityComparer<T,M> : IEqualityComparer<T> { private Func<T, T, bool> _comparer; private Func<T, M> _selector; public LambdaEqualityComparer(Func<T, M> selector) { _selector = selector; _comparer = (obj1, obj2) => Object.ReferenceEquals(obj1, obj2) || obj1 != null && obj2 != null && selector(obj1).Equals(selector(obj2)); } public bool Equals(T obj1, T obj2) { return _comparer(obj1, obj2); } public int GetHashCode(T obj) { return _selector(obj).GetHashCode(); } } /// <summary> /// Filters the enumerable to contain only distinct elements using a custom comparator. /// </summary> /// <param name="comparator">a lambda that returns true if the two objects are to be considered equal</param> public static IEnumerable<T> Distinct<T>(this IEnumerable<T> list, Func<T, T, bool> comparator) { return list.Distinct(new LambdaEqualityComparer<T>(comparator)); } /// <summary> /// Filters the enumerable to contain only distinct elements using a custom comparator. /// </summary> /// <param name="comparator">a lambda that extracts the value(s) to compare. If the selected values are equal, the objects are considered duplicate</param> public static IEnumerable<T> Distinct<T, TElem>(this IEnumerable<T> list, Func<T, TElem> selector) where TElem : IComparable { return list.Distinct(new LambdaEqualityComparer<T, TElem>(selector)); }

čtvrtek 21. července 2011

System.Web.Mvc.UpdateModel() throws exceptions after succeeding to update an object

Yes, the message is right. Even though the docs claim that it throws "System.InvalidOperationException: The model was not successfully updated."

The catch is that it throws the exception even if the model was successfully updated. Even if there was nothing to update at all. Even if there is a custom model binder for the type of the object you are trying to update, you step through the code and everything in the update works fine, all the properties are updated as they should, everything validates, the last line of your code returns exactly what it should and then KABOOOOM.

The model of type 'XXXXXX' could not be updated

Luckily in this particular case the source code is available so after some time with the sources of ASP.Net MVC you can find the reason. The (censored) who wrote the code decided to throw the exception whenever there is an error in the ModelState dictionary after updating the model. Sounds right, or not? Wait! What if there was something already before the UpdateModel() call? What if some other model failed, was handled and now I need to import some of the data into another object ... no way, as soon as there's an error, you get an exception. Your error, his error, their error, who the heck cares. Kabooom. Hooooray, we have an excuse to throw an exception!


Now if you don't really mind whether the update worked or not you can just use TryUpdateModel() and ignore the incorrect result. If you do care ... good luck.

čtvrtek 14. července 2011

MSSQL and WEEKDAY

OK. So you can set which day of the week is the "first" and then the DATEPART(weekday,@date) returns a number from 1 to 7 with the specified day being "1". The documentation is rather convoluted, but well ... what would you expect. So everything is nice and dandy isn't it?

No it is not. The catch is that the SET DATEFIRST is not stored with the stored procedure or function, but rather taken from the current connection. So you write for example a function that returns the first Monday at least N days after a specified date and ... pray that someone for whatever reason doesn't set DATEFIRST to anything else than it was set to when you tested the function. Cause the function doesn't remember what it was set to when it was parsed, you can't set it from within the function and there is no way to pass that option to DATEPART() explicitely.

Now that's what I call a stupid interface.


CREATE FUNCTION dbo.GetWeekDay(@Date datetime) RETURNS int
AS
BEGIN
Declare @day int
set @day = 1 + ((@@DATEFIRST + DATEPART( weekday, @Date) - 2) % 7);
return @day
END
go

At last something that's consistent. Agrrrrrr.

pondělí 13. června 2011

Trailing slash in URLs

We are working on an eShop using ASP.Net MVC. The client wanted the URLs to look nice ... no big deal, URLs look nice in MVC, blah.com/detail/15, blah.com/category/45, ...
Not nice enough. We want the name of the article/category in the URL like this: blah.com/15/of_mice_and_men
OK, we are generating all URLs using MVC Futures so there's always some Html.Link("blah", MVC.Detail.Index(Model.ArticleId)) so how can I tweak this to generate that URL?

First thing ... make sure we accept them:

routes.MapRoute(
  "Detail and name",
  "detail/{id}/{name}/",
  new { controller = MVC.Detail.Name, action = MVC.Detail.ActionNames.Index },
  new { id = @"^\d+$" } 
);

next we need to add the name to the RouteDataDictionary somehow. We could add the name as a parameter to the action (even though it doesn't need it) and call MVC.Detail.Index(Model.ArticleId, Model.ArticleName), but we have that on quite a few places already and we do not always have the name handy. Mkay, let's tweak some .tt In this case the T4MVC.tt. And let's do it in a gerenal way ... whenever there is a protected method RenderLink_<ActionName> in the controller, let's call it from the generated pseudoaction in the T4MVC_<ControlerName>Controller in the <ControllerName>Controller.generated.cs and let it tweak the RouteValueDictionary as needed.
Then all that is left is adding


protected void RenderLink_Index(T4MVC_ActionResult callInfo) {
  if (callInfo.RouteValueDictionary.ContainsKey("id") && callInfo.RouteValueDictionary["id"] is int) {
   callInfo.AddRouteValue("name", Article.TitleForId((int)callInfo.RouteValueDictionary["id"]).EscapeForNiceUrl());
  }
 }

into the controller and all URLs to details look as requested.

Until they come again that they want a slash at the end of the URL. OK, fine, but how? Including or not the slash in the MapRoute makes no difference. OK, the route object has some GetVirtualPath, is this what I need? I could let the inherited implementation to generate the URL and then append or insert (remember, there may be a query or hash in the URL!) the slash.

Now let's add (copy&paste&tweak) the extension methods to simplify adding the routes


public static class RouteCollectionExtensions {
  public static Route MapRouteWithSlash(this RouteCollection routes, string name, string url) {
   return MapRouteWithSlash(routes, name, url, null /* defaults */, (object)null /* constraints */);
  }
 
  public static Route MapRouteWithSlash(this RouteCollection routes, string name, string url, object defaults) {
   return MapRouteWithSlash(routes, name, url, defaults, (object)null /* constraints */);
  }
 
  public static Route MapRouteWithSlash(this RouteCollection routes, string name, string url, object defaults, object constraints) {
   return MapRouteWithSlash(routes, name, url, defaults, constraints, null /* namespaces */);
  }
 
  public static Route MapRouteWithSlash(this RouteCollection routes, string name, string url, string[] namespaces) {
   return MapRouteWithSlash(routes, name, url, null /* defaults */, null /* constraints */, namespaces);
  }
 
  public static Route MapRouteWithSlash(this RouteCollection routes, string name, string url, object defaults, string[] namespaces) {
   return MapRouteWithSlash(routes, name, url, defaults, null /* constraints */, namespaces);
  }
 
  public static Route MapRouteWithSlash(this RouteCollection routes, string name, string url, object defaults, object constraints, string[] namespaces) {
   if (routes == null) {
    throw new ArgumentNullException("routes");
   }
   if (url == null) {
    throw new ArgumentNullException("url");
   }
 
   Route route = new RouteWithSlash(url, new System.Web.Mvc.MvcRouteHandler()) {
    Defaults = new RouteValueDictionary(defaults),
    Constraints = new RouteValueDictionary(constraints),
    DataTokens = new RouteValueDictionary()
   };
 
   if ((namespaces != null) && (namespaces.Length > 0)) {
    route.DataTokens["Namespaces"] = namespaces;
   }
 
   routes.Add(name, route);
 
   return route;
  }
 
 }

and

routes.MapRouteWithSlash(
  "Detail and name",
  "detail/{id}/{name}/",
  new { controller = MVC.Detail.Name, action = MVC.Detail.ActionNames.Index },
  new { id = @"^\d+$" }
 );


and we have the slash :-)

pondělí 4. dubna 2011

cannot derive from sealed type 'System.ComponentModel.EditorAttribute'

Yep, lovely. Yet another sealed class. Why?!?

OK, so I wrote a Visual Studio plugin that extends the Entity Framework designer. Everything's working fine. Well ... mostly ... the fact that if and only if there is a plugin, any validation problems in the updated .edmx are fatal and attributed to the plugin without the user having any chance to fix the problems ... in 99.784% of cases caused by the original code ... yeah, that's pretty annoying ... the only solution is to write a copy of the .edmx into a different file just before the EF Designer starts the validation and then replace the .edmx by this copy and fix the huge "Hey, I don't know what's the primary key for this view" problem.

Anyway ... most of the attributes I need to add to the properties that I want to display in the EF Designer are kinda OK. [DisplayName("...")], ["Description("...")], [Category("..")], [DefaultValue(...)]. All that's OK.

If I want a dropdown I just define an enum and it works automatically. (And if I want a dropdown with a dynamic list of options it ... well ... I haven't found a way to do that).

Then if I want a multiline input for the property, I know how to do it, it's just an attribute. An attribute that looks like this:

[EditorAttribute(typeof(System.ComponentModel.Design.MultilineStringEditor), 
 typeof(System.Drawing.Design.UITypeEditor))]

Lovely, isn't it?

OK, so I thought I could define subclass (named for example MultiLineAttribute) that'd use the inherited constructor with those values:


public class MultiLineAttribute : System.ComponentModel.EditorAttribute {
  public MultiLineAttribute()
   : base(typeof(System.ComponentModel.Design.MultilineStringEditor),
    typeof(System.Drawing.Design.UITypeEditor)) { }
 }
Nope. Cannot derive from sealed type.

Why?!? Why the heck does the silly class have to be seaeaeaeaealed?

pátek 4. února 2011

LIKE in LINQ to Entities

For whatever reason there is (as far as Google searches suggest) no way to use LIKE in LINQ to Entities.
You can use LIKE in EntitySQL though so ... would you like a like in your LINQ?

No big deal actually.

Add

        <Function Name="String_Like" ReturnType="Edm.Boolean" ef4ex:RenameTo="Like">
          <Parameter Name="searchingIn" Type="Edm.String" />
          <Parameter Name="lookingFor" Type="Edm.String" />
          <DefiningExpression>
            searchingIn LIKE lookingFor
          </DefiningExpression>
          <ef4ex:CodeBlock>
            throw new Exception("Not implemented");
          </ef4ex:CodeBlock>
        </Function>

somewhere into the

<edmx:Runtime><edmx:ConceptualModels><Schema Namespace="Your.Namespace"
...>
and then
[System.Data.Objects.DataClasses.EdmFunction( "Your.Namespace", "String_Like")]public static Boolean Like(this String searchingIn, String lookingFor) {
 throw new Exception("Not implemented");
}
into a static class (the name doesn't matter) in one the namespaces you tend to be "using" et voila ...

var results = db.EntitySet.Where(e => e.FooBarBaz.Like("%foo%bar%")); 

Big deal, right? (Ignore or remove the ef4ex: attributes and tags, they are used by our customized template so that the C# code above gets generated automatically. If you decide to keep them add xmlns:ef4ex="http://jenda.krynicky.cz/schemas/EF4ex" attribute into the root tag of the .edmx file.)

So what's the catch? There are two ... related. 

First if you use two .edmx files in your project you either have to make sure you are only "using" one of the namespaces in each file (so that the compiler knows which extension method Like() do you mean) or have to rename one of the methods (in the C# code) so that you can access both, but then you have to make sure you always use the right one in each query.

The second is that you can't use this solution somewhere deep within a library that's to be reused with different projects. The Like() is tied fast to the .edmx. If I find a way to overcome this restriction, I'll update this post!

pondělí 10. ledna 2011

C# constructors

As usual, this is yet another in the series of complaints about C#, this time about constructors. Let me state right away that I do believe the syntax of constructors in C# is stupid. It comes as no surprise then that the syntax comes from C++. When it comes to syntax the authors of C and later C++ made quite a few stupid decisions, but I ain't gonna talk about the famous allaroundfix types of C or anything just now. So what do I hate about constructors in C#?
The fact that "A constructor looks very much like a method, but with no return type and a name which is the same as the name of the class". I don't mind the missing return type, what I do mind is the "name which is the same as the name of the class". Why? WHY? WHY?!? Why the fsck would I want to have to repeat the same name over and over again? Especially when constructors, unlike other methods are NOT inherited?

Does

 class BlaBlaBlaBla : BleBleBle {
   public BlaBlaBlaBla( Something one, OrOther two) : base(one, two) {}

ring a bell? This is annoying by itself, but the name of the class repeated as the name of the constructor, makes it about 134.7845% worse. Imagine you need to create several subclasses of a common parent! Instead of copying the first ten or so lines of the first subclass and changing JUST AND ONLY the class name on top, you have to change the name on several places. And then if you happen to add another constructor to the base class and want the subclasses to have it as well ... no, it's not automatic, not even a copy&paste job ... you have to go and change the stupid constructor name in each and every silly subclass.

Thank you very much!

It's funny that if I want to "call" one constructor from another, I do not have to repeat the name

  public BlahBlahBlah(some parameters) : this() {

is enough. WHY? Or rather WHY isn't "this" enough on both places? Why couldn't it be

  public this(some parameters) : this() {

Well it could not. It would be too convenient.

středa 24. listopadu 2010

The specified method 'xxx' on the type 'yyy' cannot be translated into a LINQ to Entities store expression because the instance over which it is invoked is not the ObjectContext over which the query in which it is used is evaluated.

I have a method defined in the partial class for one of the entities like this:

public bool IsAnonymous() {
  return (this.Roles_ & UserRoles.Registered) == 0;
 }



This of course doesn't work within LINQ to Entities queries, because the EF provider for LINQ doesn't know how to translate that to SQL so that it could send that to the database. No problem according to the docs. You can define a "Model Defined Function" and tell the EF to use that:

        <Function Name="IsAnonymous" ReturnType="Edm.Boolean" >
          <Parameter Name="user" Type="Kosmas.Models.User"/>
          <DefiningExpression>
            BitWiseAnd(user.Roles, 1) = 0
         </DefiningExpression>
        </Function>
and

[System.Data.Objects.DataClasses.EdmFunction("Kosmas.Models", "IsAnonymous")]
 public bool IsAnonymous() {
  return (this.Roles_ & UserRoles.Registered) == 0;
 }


Or can you?


Well you can't. If you try this you get a very informative error: "The specified method 'Boolean IsAnonymous()' on the type 'Kosmas.Models.User' cannot be translated into a LINQ to Entities store expression because the instance over which it is invoked is not the ObjectContext over which the query in which it is used is evaluated."


A quick Google search did not get anything useful. The only suggestions were to either change the method so that instead of a User instance I call it on the context (making the syntax rather ... silly). Or use Entity SQL (which I'd rather not either).


So I tried whether the example in Programming Entity Framework book actually works and noticed one difference. In the example they were adding the [EdmFunction] attribute to an extension method, while I'm adding it to a plain old ordinary one.


OK, let'ts try that. Let's remove the IsAnonymous method from the partial class and add


public static class Functions {
  [System.Data.Objects.DataClasses.EdmFunction("Kosmas.Models", "IsAnonymous")]
  public static bool IsAnonymous(this User obj) {
   return (obj.Roles_ & UserRoles.Registered) == 0;
  }
 }
et voila, it works. I would not call this bug ... if it wasn't. But it is! Anyway, if you do get the nonsensical error message, check whether the method is an ordinary method or an extension one. And see if you can change it from one to the other.