简体   繁体   中英

Foreign Key creation in EF Core code first

I have 2 models:

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. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. 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. Other Keys work fine. What's wrong with OrgId?

EF doesn't understand the relationship between the two entities so you might need to clarify using fluent API in your "OnModelCreating" method.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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