[英]In c# app, how to connect foreign key of subtask table in SQL?
I am trying to create a Task Management System using C# Web API & SQL Server.我正在尝试使用 C# Web API 和 SQL Server 创建一个任务管理系统。
Here is what I am trying to achieve:这是我想要实现的目标:
Here are some of my current files:以下是我目前的一些文件:
Task DTO:任务 DTO:
public class TaskDto
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime StartDate { get; set; }
public DateTime FinishDate { get; set; }
public string Status { get; set; }
}
Task.cs:任务.cs:
public class Task
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime StartDate { get; set; }
public DateTime FinishDate { get; set; }
public string Status { get; set; }
}
Subtask.cs:子任务.cs:
public class SubTask
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Status { get; set; }
}
With the above code, I'm currently, able to POST & GET a Task, but I am struggling to add the Sub-Task part.使用上面的代码,我目前能够发布和获取任务,但我正在努力添加子任务部分。
Can someone please advise what I need to do in order to be able to meet this requirement?有人可以建议我需要做什么才能满足此要求吗?
Thanks a lot in advance非常感谢提前
Better approach would be to add property nullable ParentTaskId
, which is nothing but the task id of the parent task.更好的方法是添加属性为 nullable
ParentTaskId
,它只是父任务的任务 ID。 I'm considering that task and sub task have same properties.我正在考虑该任务和子任务具有相同的属性。
Otherwise create a separate class for sub task and add nullable parentTaskId
to it as foreign key.否则为子任务创建一个单独的类并将可为空的
parentTaskId
添加到它作为外键。
Your classes would link up like this...你的课程会像这样连接起来......
public class Task
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<SubTask> SubTask { get; set; }
}
public class SubTask
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int? TaskId { get; set; }
public Task Task { get; set; }
}
You can see that Task
has a collection of SubTask
and SubTask
has a reference back to Task
with a Task
property and a TaskId
.您可以看到
Task
有一个SubTask
的集合,而SubTask
有一个对Task
的引用,带有一个Task
属性和一个TaskId
。
Update : Since you're not using EF code-first, as I initially thought.更新:因为您没有像我最初认为的那样优先使用 EF 代码。
Your DTO could just have a list of SubTask, something like this:您的 DTO 可能只有一个 SubTask 列表,如下所示:
public class TaskDto
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual List<SubTask> SubTask { get; set; }
}
Then, you could do something like:然后,您可以执行以下操作:
var tasks = (from t in _db.Tasks
join st in _db.Sub Tasks on st.Id equals t.SubTaskId
select new TaskDto
{
Id = t.Id,
Name = t.Name,
Description = t.Description,
SubTask = st
});
This is all hand written, but it'll be along these lines.这都是手写的,但它会沿着这些路线。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.