Zero or One To Many in Entity Framework

c# entity-framework entity-framework-6

Question

My situation is as follows: The Periodic Task entity can have many Tasks, but a Task can have none or only a Periodic Task associated with it. That is, I need the foreign key of Task Periodic on Task to be null. However, I am not able to do this configuration through the Entity Framework, even with the statement:

public int? PeriodicTaskID

What are the possible solutions?

Thank you very much.

public class Task
{
    public int TaskID { get; set; }

    public int? PeriodicTaskID { get; set; }

    public virtual PeriodicTask PeriodicTask { get; set; }
}

public class PeriodicTask
{
    public int PeriodicTaskID { get; set; }

    public virtual ICollection<Task> Tasks { get; set; }
}
1
0
9/5/2018 9:01:51 PM

Popular Answer

You can define the relation via Data Annotations like this;

public class Task
{
    public int TaskID { get; set; }

    public int? PeriodicTaskID { get; set; }
    [ForeignKey("PeriodicTaskID ")]
    public virtual PeriodicTask PeriodicTask { get; set; }
}

via Fluent API;

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    //..
    modelBuilder.Entity<Task>()
        .HasOne(t => t.PeriodicTask)
        .WithMany(pt => pt.Tasks);
}
0
9/5/2018 9:26:01 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow