Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

c# - LINQ to SQL: How To Extend An Entity Class With A Column Alias

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...