2

I want to do this:

public static void SetStringsToBeNonUnicode(this EntityTypeConfiguration<T> config) 
{

}

compiler doesn't like the <T> in there, what is the correct syntax for this?


more context, EntityTypeConfiguration is an EntityFramework class, defined as

public class EntityTypeConfiguration<TEntityType> : StructuralTypeConfiguration<TEntityType> where TEntityType : class

This is what is causing my headache.

What I really want to end up with is being able to do something like this when configuring dbcontext class:

public class ReceiptEntityConfiguration: EntityTypeConfiguration<ReceiptEntity>
{
    public ReceiptEntityConfiguration()
    {
        ToTable("vReceipt");
        HasKey(r => r.ReceiptId);
        this.SetStringsToBeNonUnicode();  //I want to make all string fields for this entity type (ReceiptEntity in this case) to be treated as not unicode.
        ...etc etc
    }
}

EF6.0 handles this with Lightweight Conventions, but I can't use the beta bits for prod.

BlackICE
  • 8,816
  • 3
  • 53
  • 91
  • See http://msdn.microsoft.com/en-us/library/twcad0zb.aspx – Tim S. Jul 10 '13 at 19:47
  • Tim was almost there, this provides the answer: http://stackoverflow.com/questions/68750/how-do-you-write-a-c-sharp-extension-method-for-a-generically-typed-class – BlackICE Jul 11 '13 at 11:28

1 Answers1

5

You need to specify the T as a type parameter for the function. You do that like this:

public static void SetStringsToBeNonUnicode<T>(this EntityTypeConfiguration<T> config) where T : class
{

}
BlackICE
  • 8,816
  • 3
  • 53
  • 91
Tim
  • 14,999
  • 1
  • 45
  • 68
  • 1
    I don't think `T` can be a type parameter for the containing class, can it? Conceptually, it should be possible to define an extension method within a generic or non-static class, and have its scope limited to that class, but I don't think C# will allow any declaration of methods with an `Extension` attribute within such classes. – supercat Jul 10 '13 at 20:09
  • @supercat: You are of course correct; an extension method can only be declared inside a *static*, *non-nested*, *non-generic* class. (Personally I find it slightly vexing that such a thing is even called a "class"; a class *of what* exactly? It is much more like a Visual Basic module. But we're stuck with it now.) – Eric Lippert Jul 10 '13 at 22:07
  • Good point. My parenthetical doesn't actually apply when its an extension method, so it wasn't really relevant to the question. I've removed it. – Tim Jul 11 '13 at 00:12
  • Still having compile issue: _The type 'T' must be a reference type in order to use it as parameter 'TEntityType' in the generic type or method 'System.Data.Entity.ModelConfiguration.EntityTypeConfiguration'_ – BlackICE Jul 11 '13 at 11:10
  • Looks like you just need to add this to the end of your answer: _where T : class_ – BlackICE Jul 11 '13 at 11:27