我用Linq to SQL將我的數據庫映射到基礎對象。我將所有的表拖入我的dbml中,並且它們都很好地設置。我保存的dbml並創建表示表的類等Linq製作主鍵system.nullable <int>不只是int
在我的數據庫我有一個表這樣:
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領域顯然是一個主鍵,顯然NOT 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。投標表在BidNames表中有一個外鍵,但數據是乾淨的。這裏是投標表的結構:我把你的表腳本
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
連接字符串匹配嗎?也許嘗試刪除/重新創建dbml中的表?我會認爲DBType是INT NOT NULL。 – mcknz
是的,我檢查了幾次,連接字符串是正確的。我還刪除了一個表並將其拖回到dbml,並再次將主鍵視爲可爲空。 – BKahuna