LINQ to SQL:如何使用列别名扩展实体类 [英] LINQ to SQL: How To Extend An Entity Class With A Column Alias

查看:161
本文介绍了LINQ to SQL:如何使用列别名扩展实体类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个独特的要求,我希望使用LINQ to SQL是可能的.

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

首先,我正在扩展一个较旧的应用程序,所以我被当前的数据库列名称和现有的LINQ实体类所困扰.

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

我有一个使用以下方法的LINQ包装器:

I have a LINQ wrapper with the following method:

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

IEntity看起来像:

IEntity looks like:

public interface IEntity {
  int Id { get; }
}

我现有的实体类(由LINQ生成)如下:

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; }
}

因此,为了使Widget与我的包装一起工作,我将其扩展为一个IEntity,如:

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; } }
}

当我进行类似选择时:

Repository<Widget>.Get(123);

我收到一条错误消息,说ID没有在SQL中映射.

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

我想知道的是,有一种方法可以使Widget成为IEntity并使用Id作为WidgetId的别名.已经有很多以前的代码(没有存储库包装器)编写了,它们引用了WidgetId,所以我不想更改它.

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?

推荐答案

LINQ不知道将Id转换为WidgetId.

LINQ doesn't know to translate Id to WidgetId.

在O/R设计器中,您可以将列重命名为所需的列.当您这样做时,LINQ将能够正确转换列名.在O/R设计器中重命名它们根本不会影响数据库,因此这是一个非常安全的操作.您可以打开.designer.cs文件,并查看如何使用属性"将列名映射到类属性.

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.

这篇关于LINQ to SQL:如何使用列别名扩展实体类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆