Reputation: 5356
In my ASP.Net core (1.1) Web API I have two models: Task and Feature. Initially I create one or many Tasks and then I can combine few of them to be a Feature.
For this I have written my models as following:
public class User_Task
{
[Key]
public long TaskId { get; set; }
public string What { get; set; }
[ForeignKey("FeatureId")]
public long FeatureId { get; set; }
public User_Task()
{
}
}
and Feature:
public class Feature
{
[Key]
public long FeatureId { get; set; }
public string Analyst_comment { get; set; }
public virtual ICollection<User_Task> Tasks { get; set; }
public Feature()
{
}
}
Now the problem is: I am not being able to create a task without first creating a Feature- I tried passing featureId as 0 or null for POST request of Tasks but it fails (for null I get bad request and for 0 it throws exception).
What should I modify in my models or controller or repo class to handle this situation?
Upvotes: 0
Views: 180
Reputation: 64150
You have to make your FeatureId
nullable
.
public class User_Task
{
[Key]
public long TaskId { get; set; }
public string What { get; set; }
[ForeignKey("FeatureId")]
public long? FeatureId { get; set; }
}
then add and run an migration, EF Core should be able to figure out it's an optional one-to-many relationship.
Upvotes: 3