tags:

views:

239

answers:

1

I have a unique requirement that I hope is possible with LINQ to SQL.

First off, I am extending an older application so I am stuck with current database column names and the existing LINQ entity classes.

I have a LINQ wrapper with the following method:

public T Get(int id) where T : class, IEntity {
  ...
}

IEntity looks like:

public interface IEntity {
  int Id { get; }
}

My existing entity class (generated by LINQ) looks like:

//this is not the exact code
//it is just to give you an idea
public parital class Widget {
  public int WidgetId { get; set; }
  public string WidgetName { get; set; }
}

So in order to make Widget work with my wrapper I extended it to be an IEntity like:

public partial class Widget : IEntity {
  public int Id { get { return WidgetId; } }
}

When I do a select like:

Repository<Widget>.Get(123);

I get an error saying Id is not mapped in SQL.

What I want to know is there a way for me to make Widget an IEntity and use Id as an alias of WidgetId. There is already a lot of older code written (without the repository wrapper) that references WidgetId so I don't want to have to change this.

All suggestions are appreciated. Am I going about this wrong?

+1  A: 

LINQ doesn't know to translate Id to WidgetId.

In the O/R designer you can rename the columns to whatever you need them to be. When you do this, LINQ will be able to properly translate the column names. Renaming them in the O/R designer doesn't affect the database at all, so it is a perfectly safe operation. You can open the .designer.cs file and see how the Attributes are used to map column names to class properties.

toast
I've recently read here on SO that the correct way to update a LINK to SQL model from database changes is to delete all objects on it and copy from the database again. That would destroy this change, wouldn't it? LINQ to SQL maps directly to the DB, always, so this doesn't seem like a good fit.
John Saunders
To do what he wants, this is probably the easiest way to manage it. Yes, if he changes the database and has to refresh the model, he'll have to recreate his changes. But it shouldn't happen too often and the change is a minor one in any case, easily redone.
toast
I figured this would be the solution but wanted to see if there was another way without changing the model because older code already uses WidgetId. Guess I have a little refactoring to do. Thanks.
modernzombie