简体   繁体   中英

Zero or One To Many in Entity Framework

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; }
}

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);
}

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