首先是EF核心代码,在将其设为可空之后,松开外键约束

时间:2018-11-08 11:29:28

标签: c# ef-code-first ef-core-2.1

我有这个:

public class Customer
{
    public int Id {get; set;}
    //some more properties
}

public class Payment
{
    public int Id {get; set;}
    public int CustomerId {get; set;} //foreign key
    public Customer Customer {get; set;}
}

在数据库中导致外键约束。然后,我将CustomerId设置为可空:

public class Payment
{
    public int Id {get; set;}
    public int? CustomerId {get; set;} //foreign key
    public Customer Customer {get; set;}
}

如果生成迁移脚本,则会得到以下信息:

IF NOT EXISTS(SELECT * FROM [__EFMigrationsHistory] WHERE [MigrationId] = N'MyMigration')
BEGIN

DECLARE @var2 sysname;

    SELECT @var2 = [d].[name]
      FROM [sys].[default_constraints] [d]
INNER JOIN [sys].[columns] [c] ON [d].[parent_column_id] = [c].[column_id] 
       AND [d].[parent_object_id] = [c].[object_id]
     WHERE ([d].[parent_object_id] = OBJECT_ID(N'[Payments]') AND [c].[name] = N'CustomerId');

IF @var2 IS NOT NULL EXEC(N'ALTER TABLE [Payments] 
    DROP CONSTRAINT [' + @var2 + '];');

ALTER TABLE [Payments] ALTER COLUMN [CustomerId] int NULL;
END;

GO

因此,Payments.CustomerId列现在可以为空,但是外键约束已删除。如何获取外键约束?

edit:还有一件事。在更改代码之间,我还在受保护的重写void OnModelCreating(ModelBuilder modelBuilder)中添加了此代码:

new PaymentMap(modelBuilder.Entity<Payment>());

4 个答案:

答案 0 :(得分:0)

您需要使用System.ComponentModel.DataAnnotations.Schema.ForeignKeyAttribute明确注释它:

public class Payment
{
    public int Id {get; set;}

    public int? CustomerId {get; set;} //foreign key

    [ForeignKey("CustomerId")]
    public Customer Customer {get; set;}
}

答案 1 :(得分:0)

为了使其正常工作,您应该将public virtual ICollection<Tenant> Payments { get; set;}添加到Customer

Blockquote

public class Customer
{
    public int Id { get; set; }
    public virtual ICollection<Payment> Payments { get; set; }
}

public class Payment
{
    public int PaymentId{ get; set; }
    public int? CustomerId { get; set; }
    public Customer Customer { get; set; }
}

答案 2 :(得分:0)

由于EF Core要求手动在表之间建立连接,因此您是否尝试将其写到DataContext类中?

List<Payment> Payments类和Customer覆盖方法的DataContext类中添加OnModelCreate,添加:

builder
     .Entity<Payment>()
     .HasOne(p => p.Customer)
     .WithMany(c => c.Payments)
     .HasForeignKey(p => p.CustomerId);

答案 3 :(得分:0)

我删除了本地数据库,并使用“ update-database”重新创建了它。那解决了我的问题。感谢大家的时间和精力!