假设我有以下表格和关系:
CREATE TABLE [dbo].[Customers] (
[CustomerID] [int] IDENTITY(1,1) NOT NULL,
[Description] [nvarchar](255) NOT NULL
CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED ([CustomerID] ASC)
CREATE TABLE [dbo].[Orders](
[OrderID] [int] IDENTITY(1,1) NOT NULL,
[CustomerID] [int] NOT NULL,
...
CONSTRAINT [PK_Orders] PRIMARY KEY CLUSTERED ([OrderID] ASC)
ALTER TABLE [dbo].[Orders] WITH CHECK ADD CONSTRAINT [FK_Orders_Customers]
FOREIGN KEY([CustomerID]) REFERENCES [dbo].[Customers] ([CustomerID])
我正在使用一些 T4 模板来生成简单的 POCO 类,其中每个数据库列都有一个属性。这很容易,也很有趣。事实上,我拥有的代码能够为每个表生成一个类,如下例所示
public class Customer {
public int CustomerID { get; set; }
public string Description { get; set; }
}
我现在还想创建映射表(1-N,1-1)之间关系的代码,以便获得例如像这样的类
public class Customer {
public int CustomerID { get; set; }
public string Description { get; set; }
public IList<Order> Orders { get; set; }
}
不幸的是,我的代码不起作用。这里是:
foreach ( NavigationProperty navProperty in entity.NavigationProperties.Where( p => p.DeclaringType == entity ) ) {
string elementType = ((EntityType)( (RefType)navProperty.ToEndMember.TypeUsage.EdmType ).ElementType).Name;
string relationshipName = navProperty.ToEndMember.DeclaringType.FullName;
string targetRoleName = navProperty.ToEndMember.Name;
if ( navProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ) {
<#=Accessibility.ForProperty( navProperty ) #> IList<<#=navProperty.Name#>> <#=navProperty.Name#> { get; set; }
}
}
不幸的是,这会生成这样的代码:
public class Customer {
public int CustomerID { get; set; }
public string Description { get; set; }
public IList<Orders> Orders { get; set; } // NOTE THE PLURAL IN THE TYPE NAME!!!
}
这是实体集名称而不是实体名称。我必须做些什么来解决这个问题?
注意:我将 EF 用于 .NET 3.5 版本。我还包括EF.Utility.CS.ttinclude
Visual Studio 10 中可用的。