1

I am doing an object configuration for entity framework where object A has contains a ICollection and object B does not have any relationship to this object. How would I configure this?

Here is an example of my object setup

public class A {
    public string id { get; set; }
    public ICollection<B> itemsILike { get; set;}
}

public class B {
    public string id { get; set; }
}

B doesn't need to know about A at all, but I want A to have a list of B that it can add or remove from (and can also be empty)

This is what I currently have, but I do not think this creates the correct relationship

public void Configure(EntityTypeBuilder<A> builder)
        {
            builder.HasKey(e => e.id);

            builder.HasMany(e => e.itemsILike);
        }

public void Configure(EntityTypeBuilder<B> builder)
        {
            builder.HasKey(e => e.id);
        }

Any Idea as to how to configure?

Jake_G
  • 21
  • 1
  • 4
  • *B doesn't need to know about A at all, but I want A to have a list of B that it can add or remove from (and can also be empty)* its not how you do Entity Framework One-To-Many relationship. That being said, you can have navigation property on `B` to `A` set to have [`private`](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/private) access modifier. And ensure that that the [foreign key column allows null](https://stackoverflow.com/a/2366979/4648586). – Bagus Tesa Oct 03 '19 at 01:18
  • so be would contain an extra property? – Jake_G Oct 03 '19 at 01:27
  • kind of, contractually the `-Many` part of the relationship had to have navigation property into the `One-` part as far as i know. Otherwise, Entity Framework will simply thinks its not a sql relation at all. – Bagus Tesa Oct 03 '19 at 01:28
  • So I could change B to public string id { get; set; } public ICollection as { get; set; } ? – Jake_G Oct 03 '19 at 01:41

1 Answers1

0

In order to store information about which Bs belong to an A the database needs to store this information somewhere. Without it would not be able to establish which Bs to return when you are retrieving a record of A.

This can be either via a foreign key aId on B or via a many-to-many relationship with an intermediate/join table that contains at least aId and bId.


There also is the option of storing a collection of Bs in a column of A and deserialising it in code. An example would be to store a comma-separated list of ids as a single string and add an access property/function which deseralise the data. For complex types you could use json.

Please note I'm not advocating storing json,, but if you cannot/don't_want to store the relationship as a column of B this could be a solution.


BTW. For EF Core you may want to look at No Foreign Key Property and Shadow Properties mentioned there.

tymtam
  • 31,798
  • 8
  • 86
  • 126