简体   繁体   中英

Multiple foreign keys to many tables

I have the following classes:

public class Project
{
    public int ID { get; set; }
    public string Name { get; set; }
    ...
    // Navigation
    public virtual IEnumerable<Task> Tasks { get; set; }
    //public virtual IEnumerable<Message> Messages { get; set; } // ???
}

public class Task
{
    public int ID { get; set; }
    public int ProjectID { get; set; }
    public string Name { get; set; }
    ...
    // Navigation
    //public virtual IEnumerable<Message> Messages { get; set; } // ???
}

public class Message
{
    public int ID { get; set; }
    public string Comment { get; set; }
    ...
    // Foreign Keys ??
}

Basically:

  • Project will have many Task
  • Project will have many Message
  • Task will have many Message
  • Each Message will belong to either a Project or Task

How will I write the database, as well as write the EF code to achieve this? I want to be able to use Linq syntax for eg. List<Message> messages = project.Messages.ToList();

I have found this alternative design but not sure how the navigation properties will look.

I think you are pretty much there. Could you try this?

public class Project
{
    public int ID { get; set; }
    public string Name { get; set; }
    ...
    // Navigation
    public virtual IEnumerable<Task> Tasks { get; set; }
    public virtual IEnumerable<Message> Messages { get; set; }
}

public class Task
{
    public int ID { get; set; }
    public int ProjectID { get; set; }
    public string Name { get; set; }
    ...
    // Navigation
    public virtual IEnumerable<Message> Messages { get; set; }
}

public class Message
{
    public int ID { get; set; }
    public string Comment { get; set; }
    ...
    public int? ProjectId {get;set;}
    public int? TaskId {get;set;}

    public virtual Project {get;set;}
    public virtual Task {get;set;}
}

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