0

我的数据库中存在以下表。我正在尝试设置外键,但我不确定我是否正确执行此操作。我所拥有的是表 [Application] 和表 [TestAccount] 之间的关系,其中有例如三个不同的 [Application] 行,每个行都有零个或多个 [TestAccount] 行。如果已经存在 [TestAccount] 行,我不希望能够删除 [Application] 行。

这是我的 SQL

CREATE TABLE [dbo].[Application] (
    [ApplicationId]   INT            IDENTITY (1, 1) NOT NULL,
    [Name] NVARCHAR (50) NOT NULL,
    [DataVersion] ROWVERSION,
    CONSTRAINT [PK_dbo.Application] PRIMARY KEY CLUSTERED ([ApplicationId] ASC)
);

CREATE TABLE [dbo].[TestAccount] (
    [TestAccountId]   INT            IDENTITY (1, 1) NOT NULL,
    [ApplicationId] INT,
    [Name] NVARCHAR (50) NOT NULL,
    [DataVersion] ROWVERSION,
    CONSTRAINT [PK_dbo.TestAccount] PRIMARY KEY CLUSTERED ([TestAccountId] ASC),
    CONSTRAINT fk_AccountApplication FOREIGN KEY (ApplicationId) REFERENCES Application(ApplicationId)
);

我正在尝试为 EF 配置它,这就是我目前所拥有的:

  modelBuilder.Entity<Application>()
      HasKey(a => a.ApplicationId);
      Property(a => a.ApplicationId).
      HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).
      IsRequired();

  modelBuilder.Entity<Application>().
      Property(a => a.Name).
      IsRequired().
      HasMaxLength(50);

  modelBuilder.Entity<TestAccount>()
      HasKey(a => a.TestAccountId);
      Property(a => a.TestAccountId).
      HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).
      IsRequired();

  modelBuilder.Entity<TestAccount>().
      Property(t => t.Name).
      IsRequired();

有人可以告诉我我是否正确地使用数据库中的外键来解决这个问题,并告诉我如何使用流畅的 API 配置外键。

4

1 回答 1

0

假设您的模型看起来像这样:

public class Application 
{
    public int ApplicationId { get; set; }

    public string Name { get; set; }
    public virtual ICollection<TestAccount> TestAccounts { get; set; }
}

public class TestAccount
{
    public int TestAccountId { get; set; }
    public int ApplicationId { get; set; }
    public string Name { get; set; }
    public virtual Application Application { get; set; }
}

通过 fluent 将您的 FK 映射到您的导航属性将如下所示:

    modelBuilder.Entity<Application>()
        .HasMany(a => a.TestAccounts)
        .WithRequired(t => t.Application)
        .WillCascadeOnDelete(false);
于 2013-03-05T13:13:39.663 回答