Mickael Caruso
Mickael Caruso

Reputation: 9491

Mapping of Interface is Not Supported, But Linq-Sql Object Already Implements Property

So, I created a DataContext (Linq-Sql) in VS from an existing database. It has a table called Users, thus I have a User object. In particular, I want to focus on the UserID and Username properties.

Now, I have an interface:

interface IUser
{
     int Id { get; }
     string Username { get; }
}

I want to create a partial User class and implement IUser. The reason for this is so that I can treat any User as an IUser in many places and not be concerned about the precise User class:

public partial class User : IUser
{
    public int Id
    {
         get { return UserID; }
    }
}

I don't implement the Username get property because I know that the entity object already implements it.

When I have a query like dc.Users.SingleOrDefault(p => p.Id == 5); I know that it's an error because it'll translate that call to an SQL statement and it's going to try to find the Id column, which doesn't exist - UserID exists. So I understand this mapping issue.

When I query dc.Users.SingleOrDefault(p => p.Username == "admin"), it also throws an error, BUT Username IS indeed an existing column in the database, so my impression is that no custom/additional mapping needs to take place. What am I missing?

Can someone point me to a good source on how to combat Linq vs. partial classes implement a custom interface?

Update Question: Before I try it, does anyone know if "rigging" the datacontext.designer.cs file with our custom interfaces (to implement to the classes themselves instead of in a separate partial class file) will work? Is there a consequence of doing this?

Upvotes: 3

Views: 858

Answers (1)

Ryan Allen
Ryan Allen

Reputation: 81

I've come across this before using Generics and LINQ, and the way I solved it was to change p.Id == 5 to p.Id.Equals(5) and LINQ was able to map the query.

In regards to rigging autogenerated code, I have done this in my projects, the only annoyance is having to type all the interfaces again if you regenerate your DBML file. I looked in to dynamically adding interfaces to classes and found this SO post, but I haven't tried it out yet:

What is the nicest way to dynamically implement an interface in C#?

Either way, re-typing is a much better trade off for us right now as we've been able to remove a lot of duplication in our implementation code with this method.

Unfortunately I'm not experienced enough with LINQ or .NET to explain why Equals() works when == does not :)

Upvotes: 6

Related Questions