简体   繁体   中英

How do I map one entity to many entities in Entity Framework?

I have 4 entities. They look something like this:

public abstract class Entity
{
    public Guid Id { get; set; }
    public DateTime CreationDate { get; set; }
}

public class Client :
    Entity
{
    public string Name { get; set; }
    // ...
    public IList<Note> Notes { get; set; }
}

public class Supplier :
    Entity
{
    public string Name { get; set; }
    // ...
    public IList<Note> Notes { get; set; }
}

public class Note :
    Entity
{
    public Guid EntityId { get; set; } // This points to the Id field of a Client or Supplier
    public virtual Entity Entity { get; set; }
    public string EntityName { get; set; } // "Client", "Supplier", etc.
}

Now, what I want is for this to create 3 tables, Client, Supplier, and Note. The note table needs to point to the client and supplier note on the EntityId field. What is actually happening, is that EF is adding Client_ID and Supplier_ID fields to the Note table, with foreign keys to each respective table. The effect of this is basically that notes can only be created if both client and supplier are included.

What do I need to do to make this behave the way I need?

Try this Info

this.HasOptional(t => t.Client)
                .WithMany(t => t.Notes )
                .HasForeignKey(d => d.Id);

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