我正在使用Linq to SQL将我的数据库映射到基础对象。我将所有表拖到我的dbml中,它们都设置得很好。我保存了dbml,它创建了代表表等的类。
在我的数据库中,我有一张表:
CREATE TABLE [dbo].[BidNames](
[BidNameID] [int] IDENTITY(1,1) NOT NULL,
[CustomerID] [int] NOT NULL,
[BidName] [varchar](75) NOT NULL,
CONSTRAINT [PK_BidNames] PRIMARY KEY CLUSTERED
(
[BidNameID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
BidNameID字段显然是主键,显然不是NULL。然而,Linq定义了BidNameID,如下所示:
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_BidNameID", DbType="Int")]
public System.Nullable<int> BidNameID
{
get
{
return this._BidNameID;
}
set
{
if ((this._BidNameID != value))
{
if (this._BidName1.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnBidNameIDChanging(value);
this.SendPropertyChanging();
this._BidNameID = value;
this.SendPropertyChanged("BidNameID");
this.OnBidNameIDChanged();
}
}
}
其中BidNameID定义为System.Nullable。我的数据库中的所有其他表都正确解析,因此我想知道为什么会发生这种情况。有什么想法吗?
提前致谢。
修改
我发现此问题与另一个表有关。如果我从dbml中删除Bids表并重新保存,BidNameID列将正确解析为int。如果我把Bids表放回去保存它就会回到Nullable。 Bids表在BidNames表中有一个外键,但数据是干净的。这是Bids表的结构:
CREATE TABLE [dbo].[Bids](
[BidID] [int] IDENTITY(1,1) NOT NULL,
[CustomerID] [int] NOT NULL,
[ItemID] [int] NOT NULL,
[Amount] [money] NOT NULL,
[BidName] [varchar](75) NOT NULL,
[BidTime] [datetime] NOT NULL,
[BidNameID] [int] NULL,
CONSTRAINT [PK_Bids] PRIMARY KEY CLUSTERED
(
[BidID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
ALTER TABLE [dbo].[Bids] WITH CHECK ADD CONSTRAINT [FK_Bids_BidNames] FOREIGN KEY([BidNameID])
REFERENCES [dbo].[BidNames] ([BidNameID])
GO
ALTER TABLE [dbo].[Bids] CHECK CONSTRAINT [FK_Bids_BidNames]
GO
ALTER TABLE [dbo].[Bids] WITH CHECK ADD CONSTRAINT [FK_Bids_Customers] FOREIGN KEY([CustomerID])
REFERENCES [dbo].[Customers] ([CustomerID])
GO
ALTER TABLE [dbo].[Bids] CHECK CONSTRAINT [FK_Bids_Customers]
GO
ALTER TABLE [dbo].[Bids] WITH CHECK ADD CONSTRAINT [FK_Bids_Items] FOREIGN KEY([ItemID])
REFERENCES [dbo].[Items] ([ItemID])
GO
ALTER TABLE [dbo].[Bids] CHECK CONSTRAINT [FK_Bids_Items]
GO
答案 0 :(得分:0)
我拿了你的表脚本,在我的数据库中运行并将其拖入dbml并且它没有生成为可空(VS2010,VB.NET 4.0):
<Global.System.Data.Linq.Mapping.ColumnAttribute(
Storage:="_BidNameID", AutoSync:=AutoSync.OnInsert,
DbType:="Int NOT NULL IDENTITY", IsPrimaryKey:=True,
IsDbGenerated:=True)>
Public Property BidNameID() As Integer
Get
Return Me._BidNameID
End Get
Set(value As Integer)
If ((Me._BidNameID = value) _
= False) Then
Me.OnBidNameIDChanging(value)
Me.SendPropertyChanging()
Me._BidNameID = value
Me.SendPropertyChanged("BidNameID")
Me.OnBidNameIDChanged()
End If
End Set
End Property
也许尝试其中一个或多个?
答案 1 :(得分:0)
我不一定理解为什么但是当我改变Bids表并使BidNameID字段为NOT NULL时,它修复了BidName.BidNameID字段的问题。它现在解析为int而不是nullable。