Using a Custom Data Type in Linq to SQL


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;


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.

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.