【问题标题】:How should I configure relationships between these models with Fluent API?我应该如何使用 Fluent API 配置这些模型之间的关系?
【发布时间】:2020-11-06 08:42:00
【问题描述】:

我收到此错误“在表 'Tasks' 上引入 FOREIGN KEY 约束 'FK_Tasks_Projects_ProjectId' 可能会导致循环或多个级联路径”

Project 类中的任务可以为空,用户也可以没有 TeamId。


public class Task {
    public int Id {get; set;}
    public int ProjectId {get; set;}
    public int PerformerId {get; set;}
    public User Performer {get; set;}
}

public class Project {
    public int Id {get; set;}
    public int AuthorId {get; set;}
    public int TeamId {get; set;}
    public List<Task> Tasks {get; set;}
    public User Author {get; set;}
    public Team Team {get; set;}
}

public class Team {
    public int Id {get; set;}
}

public class User {
    public int Id {get; set;}
    public int ?TeamId {get; set;}
}

【问题讨论】:

    标签: c# database entity-framework-core asp.net-core-webapi fluent


    【解决方案1】:

    这里有一个类似的帖子:Entity Framework Core: How to solve Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths

    为了简化这一点,我只需将用户的 id 捕获为项目和任务的 int(而不是用户实体)。

    public class Task {
        public int Id {get; set;}
        public int ProjectId {get; set;}
        public int PerformerId {get; set;}
    }
    
    public class Project {
        public int Id {get; set;}
        public int AuthorId {get; set;}
        public int TeamId {get; set;}
        public List<Task> Tasks {get; set;}
        public int Author {get; set;}
        public Team Team {get; set;}
    }
    
    public class Team {
        public int Id {get; set;}
    }
    
    public class User {
        public int Id {get; set;}
        public int ?TeamId {get; set;}
    }
    

    最终我会选择像这样稍微不同的结构:

    public class Task
    {
        public int TaskID { get; set; }
        public int ProjectID { get; set; }
        public int PerformerID { get; set; }
    }
    
    public class Project
    {
        public int ProjectID { get; set; }
        public int AuthorID { get; set; }
        public int TeamID { get; set; }
        public List<Task> Tasks { get; set; }
        public Team Team { get; set; }
    }
    
    public class Team
    {
        public int TeamID { get; set; }
    }
    
    public class User
    {
        public int UserID { get; set; }
        public List<Team> Teams { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-27
      • 2021-05-10
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 2013-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多