0

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; }
}
  • I recommend renaming your `Task` entity to something else because `System.Threading.Tasks.Task` is used a lot in C#/.NET nowadays so you'll end up with lots of name collisions. – Dai Sep 05 '18 at 21:03
  • Thanks for the suggestion. For now I have had no conflicts with this, but in fact is something to avoid. – Lucas Dirani Sep 05 '18 at 21:10
  • 2
    I see neither data-annotations nor fluenti api to configure your associations. How do you expect it to work without any configurations? – Erik Philips Sep 05 '18 at 21:14
  • I have created classes that inherit from EntityTypeConfiguration to configure the attributes of each entity and do the mapping. The foreign key PeriodicTask is created but does not accept null values on Task table. – Lucas Dirani Sep 05 '18 at 21:24
  • 1
    That model should configure correctly by convention, without either annotations of fluent mapping. And it looks correct, except that the PeriodicTasks.Tasks property is not getting set. What is the error? – David Browne - Microsoft Sep 05 '18 at 21:54

1 Answers1

0

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);
}
ilkerkaran
  • 4,214
  • 3
  • 27
  • 42
  • PeriodicTaskID will be the ForeignKey by [convention](https://learn.microsoft.com/en-us/ef/ef6/modeling/code-first/conventions/built-in). [HasOne](https://stackoverflow.com/questions/44481675/hasone-not-found-in-ef-6) is not in EF6. – Steve Greene Sep 06 '18 at 13:00