Foreign Key creation in EF Core code first

c# entity-framework entity-framework-core

Question

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?

1
0
11/10/2017 2:39:27 PM

Popular Answer

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.

0
11/10/2017 2:58:33 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow