【问题标题】:Correct way to create a foreign key based on type, in SQL Server and Entity Framework Core在 SQL Server 和 Entity Framework Core 中基于类型创建外键的正确方法
【发布时间】:2021-01-06 15:36:13
【问题描述】:

我在我的应用程序中使用 Entity Framework Core 和 SQL Server。我对外键非常熟悉,但我想学习如何正确地为基于类型的实体提供外键。

例如:

父类AppUser:

CREATE TABLE AppUser
(
    Id INT NOT NULL PRIMARY KEY IDENTITY(1, 1),
    Name VARCHAR(255) NOT NULL,
    UserTypeId SMALLINT NOT NULL --  !This is the important part for me! if 0 = Student if 1 = Teacher
);

CREATE TABLE Student
(
    Id INT NOT NULL PRIMARY KEY IDENTITY(1, 1),
    AppUserId INT NOT NULL,

    CONSTRAINT FK_Student_AppUser FOREIGN KEY (AppUserId)
    REFERENCES AppUser(Id)
);

CREATE TABLE Teacher
(
    Id INT NOT NULL PRIMARY KEY IDENTITY(1, 1),
    AppUserId INT NOT NULL,

    CONSTRAINT FK_Student_AppUser FOREIGN KEY (AppUserId)
    REFERENCES AppUser(Id)
);

我的问题:有没有更好的方法来建立这种关系。因为在 Entity Framework 中,当我尝试获取用户时,我总是需要检查 TypeId 并为类型设置 if else 块,然后对表 student 或 teacher 进行查询。任何建议都会很棒。谢谢!

【问题讨论】:

  • 你能发布一些代码来展示你想要实现的目标吗?你的UserTypeId 专栏——它的目的是什么?
  • @PlamenYordanov 例如,当我尝试更新学生时,我将 AppUser Id 发布到 .net web api。然后,我必须获得具有该 ID 的 AppUser。那么我应该创建一个 if 块,例如: if(user.TypeId == 0) // update student.我直接想在不写 if 块的情况下获取学生对象
  • 好吧,在更新特定用户之前必须满足一个条件,您必须以某种方式识别该对象。您如何获得用户?

标签: sql-server database asp.net-core entity-framework-core foreign-keys


【解决方案1】:

根据你的表结构,如果你想通过 AppUser Id 获取学生,你可以直接使用这段代码:

 var data = _context.Student.Include(x => x.AppUser).Where(x => x.AppUserId == userId).FirstOrDefault();

接下来,只需要区分data的参数即可。

如果data为null,则表示AppUser的Id不是学生而是老师(表示UserTypeId字段值为1),否则可以更新学生字段你想要的。

           if (data != null)
            {
               //update student
            }

【讨论】:

    猜你喜欢
    • 2019-10-15
    • 2017-10-19
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 2016-12-16
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多