首先是C#数据库:引用自己的表';s专栏发行
我为这个难以理解的标题感到抱歉 通常,这就是我正在做的:首先是C#数据库:引用自己的表';s专栏发行,c#,foreign-keys,entity,ef-database-first,C#,Foreign Keys,Entity,Ef Database First,我为这个难以理解的标题感到抱歉 通常,这就是我正在做的: 添加ADO.NET实体数据模型(包括外键) 表现在在我的项目中自动生成为类 现在我来解决这个问题,说我有两张桌子: CREATE TABLE [VoucherType] ( [ID] nvarchar(10) not null Constraint [PK_VoucherType] Primary Key Clustered , [VNName] nvarchar(50) default '' not null,
- 添加ADO.NET实体数据模型(包括外键)
- 表现在在我的项目中自动生成为类
CREATE TABLE [VoucherType]
(
[ID] nvarchar(10) not null Constraint [PK_VoucherType] Primary Key Clustered ,
[VNName] nvarchar(50) default '' not null,
[ENName] nvarchar(50) default '' not null,
[Rowver] [TIMESTAMP] not null
)
CREATE TABLE dbo.[VoucherHeader]
(
[ID] INT IDENTITY(1,1) Constraint [PK_VoucherHeader] Primary Key Clustered , -- PRIMARY
[DateCreated] datetime not null,
[Description] nvarchar (512) default '' not NULL ,
[VoucherTypeID] nvarchar(10) null
Constraint [FK_VoucherHeader_VoucherTypeID] Foreign Key (VoucherTypeID) References dbo.VoucherType(ID)
)
现在,在我的代码中,我添加了一个分部类VoucherHeader,我的目标是添加一个名为VoucherTypeName的新属性,它来自VoucherType表:
public partial class VoucherHeader
{
[DataMember]
public string VoucherTypeName
{
set { }
get
{
if (VoucherType != null) return VoucherType.ENName;
else return "";
}
}
}
好了,现在我在VourcherHeader类中有了VourcherType.ENName
但如果我在VoucherHeader表中添加了一个新列,它将引用自己的列,该怎么办
alter table voucherheader add
[RelatedID] [int] null
Constraint [FK_VoucherHeader_RelatedID] Foreign Key (RelatedID) References dbo.VoucherHeader(ID)
这不起作用:
public partial class VoucherHeader
{
[DataMember]
public string RelatedDescription
{
set { }
get
{
if (VoucherHeader != null) return VoucherHeader.Description;
else return "";
}
}
}
非常感谢您的帮助 如果使用数据库优先的方法,只需在更改VoucherHeader表后从数据库更新模型即可 这可能会导致出现两个额外的导航属性:VoucherHeader1和VoucherHeader2 VoucherHeader1用于VoucheHeader集合,因为此特定实体可能是许多其他VoucherHeader实体的目标 VoucherHeader2将是您的RelatedID引用的相关实体。因此,您需要在代码中引用该实体的描述:
public partial class VoucherHeader
{
[DataMember]
public string RelatedDescription
{
set { }
get
{
if (VoucherHeader2 != null) return VoucherHeader2.Description;
else return "";
}
}
}
您可以在生成的实体类(model.tt下的VoucherHeader.cs)中检查正确的属性名称。谢谢您的回答,实际上我提出了这个,但由于工作繁忙而从未测试过,而且不太确定它是什么,只是一种预感。无论如何,非常感谢,现在一切都有意义了