Entity Framework 6 and const vs static readonly

Note: I haven’t tested this on Entity Framework Core, but I imagine the behavior is the same

Let’s say you have the following class:

public static class BlargTypes {
     public static readonly string Foo = "Bar";
}

and then you have the following LINQ query:

var result = dbContext.Blargs.Where(x => x.Blarg == BlargTypes.Foo);

then Entity Framework will generate a SQL query that looks like this:

SELECT [Id],[Blarg] FROM [Blargs] WHERE [Blarg] = @Blarg

passing in “Bar” as the parameter value for @Blarg

Now, what if the value never changes? There’s really no need for a parameterized value for @Blarg. How do you manage that?

public static class BlargTypes {
    public const string Foo = "Bar";
}

Entity Framework will generate the following query:

SELECT [Id],[Blarg] FROM [Blargs] WHERE [Blarg] = 'Foo'

In summary, if you want a parameterized query, use static readonly, otherwise use const.

Enums, C#, and Protocol Buffers

So, in the brave new world of microservice development, there’s this fancy technology called GRPC which allows you to define RPC-based microservices using Protocol Buffers as an IDL syntax and uses HTTP/2 as a transport underneath.

Now, Protocol Buffers’ IDL syntax supports enums. However, it doesn’t allow multiple enum values in different enums in the same namespace to have the same enum value, such as:

enum MyEnum {
FOO = 1;
BAR = 2;
}

enum OtherEnum {
FOO = 1;
BAR = 2;
}

What to do, what to do? The Protobuf compiler will complain, because FOO and BAR are the same name because that isn’t compatible with C++

The suggested alternative is to prefix your enum values with the name of the enum in ALL CAPS

enum MyEnum {
MYENUM_FOO = 1;
MYENUM_BAR = 2;
}

enum OtherEnum {
OTHERENUM_FOO = 1;
OTHERENUM_BAR = 2;
}

The cool thing is that the official C# compiler for Protobuf will convert this to idiomatic C# enums:

enum MyEnum {
Foo = 1;
Bar = 2;
}

enum OtherEnum {
Foo = 1;
Bar = 2;
}