没有外键的外键'值

时间:2015-03-12 11:13:49

标签: sql-server linq-to-sql sql-server-2008-r2

在我的应用程序中,我使用MS SQL Server 2008和Linq-to-SQL。我有两个表:AB,与外键相关联:B.AId => A.Id。在B.AId中是否有可能有一个值,例如-1,这意味着'没有A'并忽略外键?

我无法在NULL中使用B.AId,因为Linq-to-SQL不支持一对一或零关联(不幸的是)。

1 个答案:

答案 0 :(得分:1)

使用表A和B

创建样本模型
CREATE TABLE [dbo].[A](
    [Id] [int] NOT NULL,
    [AA] [varchar](50) NOT NULL,
    [AAA] [varchar](50) NOT NULL,
 CONSTRAINT [PK_A] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[B](
    [Id] [int] NOT NULL,
    [BB] [varchar](50) NOT NULL,
    [BBB] [varchar](50) NOT NULL,
    [AId] [int] NULL,
 CONSTRAINT [PK_B] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER TABLE [dbo].[B]  WITH CHECK ADD  CONSTRAINT [FK_B_A] FOREIGN KEY([AId])
REFERENCES [dbo].[A] ([Id])
GO

ALTER TABLE [dbo].[B] CHECK CONSTRAINT [FK_B_A]
GO

之后从数据库生成模型。即使它被识别为1对多关系,也会为表B创建导航属性A.

Linq-to-sql model

我创建了一个测试并在表B中创建了三个不同的行

  1. 使用导航属性A
  2. 使用A的ID
  3. 创建了一行而没有引用A

    using (var db = new DataClasses1DataContext())
    {
        // Add sample A row
        var sampleARow = new A()
                             {
                                 Id = 1,
                                 AA = "AA",
                                 AAA = "AAA",
                             };
    
        db.As.InsertOnSubmit(sampleARow);
        db.SubmitChanges();
    
        // Refer to sample A row using navigation property
        var sampleNewBRowWithNav = new B()
                               {
                                   Id = 1,
                                   BB = "BB1",
                                   BBB = "BBB1",
                                   A = db.As.First(),
                               };
    
        // Refer to sample A row using Id
        var sampleNewBRowWithId = new B()
        {
            Id = 2,
            BB = "BB2",
            BBB = "BBB2",
            AId = 1,
        };
    
        // No reference to A
        var sampleNewBRowWithoutA = new B()
        {
            Id = 3,
            BB = "BB3",
            BBB = "BBB3",
            AId = null  // strictly not needed, because AId is default null
        };
    
        db.Bs.InsertOnSubmit(sampleNewBRowWithNav);
        db.Bs.InsertOnSubmit(sampleNewBRowWithId);
        db.Bs.InsertOnSubmit(sampleNewBRowWithoutA);
    
        db.SubmitChanges();
    }