简体   繁体   中英

Entity Framework code first - Array of foreign keys

I have an entity with a list of other entites.
The other entities are "read only" and are only a mere association.
The meaning is that the entity should only have a list of the other entities ids and nothing more.
How can I achive this so I can have as simple as possible update graph later on?

 public class Worker
 {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    public string Name { get; set; }

    public double Age { get; set; }

    public int? ManagerID { get; set; }

    [ForeignKey("ManagerID")]
    public virtual Worker Manager { get; set; }

    /// <summary>
    /// This is just an association to the tasks. 
    /// An update graph should ignore the entity itself since 
    /// the task is immutable in this context!!!
    /// </summary>
    public virtual ICollection<Task> AssignedTasks { get; set; }
}

public class Task
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    public string TaskName { get; set; }

    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }

    /// <summary>
    /// This is just an association to the workers. 
    /// An update graph should ignore the entity itself 
    /// since the worker is immutable in this context!!!
    /// </summary>
    public virtual ICollection<Worker> AssignedWorkers { get; set; }
}

I need just the entities ids ... BUT the collections are used to build the DB schema...

In the example above - On update the worker just need to update the tasks ids that were assigned to him and not their whole data

You can mark the actual list of entities as private virtual. This will prevent outside access. Then create the list of ids as a property that does a .Select(e => e.Id) on your entity list. The entity list would only be able to be modified from inside the parent entity.

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