【问题标题】:EF Code First ErrorEF 代码第一个错误
【发布时间】:2015-05-06 10:00:15
【问题描述】:

我正在尝试使用 Code First 创建一些表。这是我的代码:

public class Country
{
    [Key]
    public int Id { get; set; }
    public string CountryName { get; set; }
}

public class State
{
    [Key]
    public int Id { get; set; }
    public string StateName { get; set; }
    public int CountryId { get; set; }
    public Country Country { get; set; }
}

public class Customer
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public int CountryId { get; set; }
    public int StateId { get; set; }
    public virtual Country Country { get; set; }
    public virtual State State { get; set; }
}

public class ProductContext : DbContext 
{
    public DbSet<Country> Country { get; set; }
    public DbSet<Customer> Customer { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

当我执行此代码时,会出现以下错误:

引入 FOREIGN KEY 约束 表 'State' 上的 'FK_dbo.State_dbo.Country_CountryId' 可能会导致循环 或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。无法创建 约束。查看以前的错误。

但我希望状态表中的 CountryId 是外键。我在这里想念什么?谁能指导我实现这一目标的正确方法?

【问题讨论】:

    标签: entity-framework


    【解决方案1】:

    Entity Framework 担心这里的删除-因为UserCountryState 有直接关系,而State 也与Country 有直接关系,你实际上有一个潜在的循环User -> State -> Country -> User 这意味着如果在您删除一个用户时启用了级联删除,您可能会删除数据库中的所有内容。

    答案在错误消息中 - 通过禁用其中一些关系的级联删除(这是合乎逻辑的 - 删除用户并不意味着您要删除他们的州和国家/地区),您将避免这种风险。正如你想象的那样this has come up on SO before.

    顺便说一句,在UserState 上使用Country 看起来像是有问题的非规范化 - 可能有充分的理由,但这种情况发生的频率比您预期的要少。

    【讨论】:

    • 谢谢。有效。这会禁用我将来可能添加的任何其他表的级联删除吗?
    • 创建表 [dbo].[Customer] ( [Id] INT IDENTITY (1, 1) NOT NULL, [Name] NVARCHAR (MAX) NULL, [CountryId] INT NOT NULL, [StateId] INT NOT NULL, CONSTRAINT [PK_dbo.Customer] PRIMARY KEY CLUSTERED ([Id] ASC), CONSTRAINT [FK_dbo.Customer_dbo.Country_CountryId] FOREIGN KEY ([CountryId]) REFERENCES [dbo].[Country] ([Id]), CONSTRAINT [FK_dbo.Customer_dbo.State_StateId] 外键 ([StateId]) 参考 [dbo].[State] ([Id]) );
    • 创建表 [dbo].[State] ( [StateId] INT IDENTITY (1, 1) NOT NULL, [CountryID] INT NOT NULL, [StateName] VARCHAR (100) NOT NULL, PRIMARY KEY CLUSTERED ([StateId] ASC), CONSTRAINT [FK_State_Country] FOREIGN KEY ([CountryID]) REFERENCES [dbo].[Country] ([CountryId]) );
    • CREATE TABLE [dbo].[Country] ([CountryId] INT IDENTITY (1, 1) NOT NULL, [CountryName] VARCHAR (100) NOT NULL, PRIMARY KEY CLUSTERED ([CountryId] ASC) );
    • 这是我用来创建表的 SQL(先留下代码)。这里 CountryID 在客户和州上。你能给我建议我应该遵循的最佳做法吗
    猜你喜欢
    • 2015-11-23
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 1970-01-01
    相关资源
    最近更新 更多