Sraban75
Sraban75

Reputation: 117

Is it possible to refer foreign key with both classes in C#?

Suppose I have two classes Country and Currency, and I want to create a relation between them using EF.

public class Country
{
    public long Id {get; set;}
    public string Name {get; set;} 

    public long? CurrencyId {get; set;}
    public Currency Currency {get; set;}
}

public class Currency
{
    public long Id {get; set;}
    public string Name {get; set;} 

    public long? CountryId {get; set;}
    public Country Country {get; set;}
}

I can't manage this, I have some models in the same type. Like User and Organization.

An Organization has Nullable UserId, and User has a Nullable organization. How can I manage this?

Upvotes: 0

Views: 307

Answers (2)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89316

You can absolutely have these kinds of relationships, but they have to be configured correctly, and sometimes you have to insert entities and later update them to work around the enforcement of FKs at insert-time rather than commit-time.

In particular EF has no convention to match up the inverse navigation properties when there are multiple relationships between two entities.

EG

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int DepartmentId { get; set; }

    [InverseProperty(nameof(EfCore3Test.Department.Members))]
    public Department Department { get; set; }

    [InverseProperty(nameof(EfCore3Test.Department.Manager))]
    public virtual ICollection<Department> ManagedDepartments { get; } = new HashSet<Department>();
}
public class Department
{
    public int Id { get; set; }
    public virtual ICollection<Person> Members { get; } = new HashSet<Person>();
    public Person Manager { get; set; }
    public int ManagerId { get; set; }
}

And you typically can't have cascading behavior on all the FKs, so you configure at least one to not cascade.

modelBuilder.Entity<Department>()
            .HasMany(d => d.Members)
            .WithOne(m => m.Department)
            .OnDelete(DeleteBehavior.NoAction);

Upvotes: 0

gh9
gh9

Reputation: 10703

public class Country
{
    public long Id {get; set;}
    public string Name {get; set;} 

    public long? CurrencyId {get; set;}
    [ForeignKey("CurrencyId")]
    public virtual Currency Currency {get; set;}
}

public class Currency
{
    public long Id {get; set;}
    public string Name {get; set;} 

    public long? CountryId {get; set;}
    [ForeignKey("CountryId")]
    public virtual Country Country {get; set;}
}

you will need to reference using System.ComponentModel.DataAnnotations.Schema;

Upvotes: 1

Related Questions