tags:

views:

53

answers:

1

Is there a way to use a custom data type in the entity returned by Linq to SQL?

Say I have a data type like this:

public struct CustomerNumber : IEquatable<string>
{
    private string _value;

    public static implicit operator CustomerNumber(string value)
    {
        return new CustomerNumber { _value = value };
    }

    ...
}

It also defines operators for == != and so on.

When I try to replace one of the properties in the returned entity I get an exception Invalid cast from 'System.String' to 'CustomerNumber' even though you can assign the CustomerNumber from a string.

Is this not possible or am I doing something wrong?

Edit - Clarification:

The CustomerNumber is used as a data type on the entity that gets generated by the Linq to SQL. The Exception occurs when trying to query the database. It's not something I'm trying to cast, it's somewhere inside the LinqToSQL magic that things go wrong.

My code looks something like this:

var customers = DataContext.Customers;

Edit:

It turns out that if your struct implements an explicit operator it works or rather, it's working with a struct that implements an explicit operator to convert from string to the type but not if it is to convert from System.Int32 to the type.

Edit again: It still does not work.

+1  A: 

I think the only way you'll be able to do this is to write it as a property in the partial class which L2S generates. If you make the Column property private, you can keep it a string, and then just use it as a backing store for your custom property exposing your custom type.

codekaizen
I ended up doing this way even if it is not the way I wanted to do it from the start.
Kristoffer L
This solution does not work with queries like `DataContext.Customers.Where(w => w.CustomProperty == 1);` as it has no translation to SQL.
Kristoffer L
Right, you can't query on it, of course. L2S's implementation of IQueryable doesn't know how to map it. I'd wonder if there is a way to provide a custom AttributeMappingSource or change the MetaModel to tell it how to map the custom type.
codekaizen
I don't understand what Linq does internally that makes it impossible to cast from the Int or string to my custom data type. I have tried all kinds of casts outside of Linq and they work flawlessly. If only there were a way to see the code that tries to do the cast maybe I can find the problem.
Kristoffer L
The reason is that Linq to SQL doesn't execute code, like you are doing everywhere else. It merely interprets it and converts it into SQL, where the conversion doesn't make sense.
codekaizen