简体   繁体   English

首先在EF Core代码中创建外键

[英]Foreign Key creation in EF Core code first

I have 2 models: 我有2个型号:

public class GaOrgOrders
{
    public virtual Guid Id { get; set; }

    [ForeignKey("GaOrganizations")]
    public virtual Guid OrgId { get; set; }

    [ForeignKey("GaApps")]
    public virtual Guid AppId { get; set; }

    [ForeignKey("GaOrgUserOrganizations")]
    public virtual Guid OrgUserId { get; set; }

    [ForeignKey("GaServicesTariffs")]
    public virtual Guid ServiceTariffId { get; set; }

    public virtual bool IsTemporary { get; set; }

    public virtual Apps GaApps { get; set; }

    public virtual Organizations GaOrganizations { get; set; }

    public virtual OrgUserOrganizations GaOrgUserOrganizations { get; set; }

    public virtual GaServicesTariffs GaServicesTariffs { get; set; }
}

and

public class GaOrganizations
{
    public virtual Guid Id { get; set; }

    public virtual string Name { get; set; }

    public virtual bool IsDeleted { get; set; }
}

When I try to update database and add these tables I get an error: 当我尝试更新数据库并添加这些表时,出现错误:

Introducing FOREIGN KEY constraint 'FK_GaOrgOrders_GaOrganizations_OrgId' on table 'GaOrgOrders' may cause cycles or multiple cascade paths. 在表“ GaOrgOrders”上引入FOREIGN KEY约束“ FK_GaOrgOrders_GaOrganizations_OrgId”可能会导致循环或多个级联路径。 Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. 指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。 Could not create constraint or index. 无法创建约束或索引。 See previous errors. 请参阅先前的错误。

If I remove "ForeignKey" attribute from OrgId property - error disappears, but it creates in database a second field(GaOrganizationsId) and makes it a FK. 如果我从OrgId属性中删除“ ForeignKey”属性-错误消失了,但它在数据库中创建了第二个字段(GaOrganizationsId)并将其设置为FK。 Other Keys work fine. 其他键工作正常。 What's wrong with OrgId? OrgId怎么了?

EF doesn't understand the relationship between the two entities so you might need to clarify using fluent API in your "OnModelCreating" method. EF无法理解两个实体之间的关系,因此您可能需要在“ OnModelCreating”方法中使用流利的API进行澄清。

Using something like 使用类似

modelBuilder.Entity<ClassB>().HasRequired(x => x.ClassA).WithOptional(x => x.ClassB);

where ClassA and ClassB are my entities having a 1 to 0 or 1 relationship between them. 其中ClassA和ClassB是我的实体,它们之间具有1到0或1的关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM