标签: ef-code-first-mapping

如何在ASP.NET MVC中使用Entity Framework将记录插入具有外键的表中

我是Entity Framework代码优先的新手。这是我在ASP.NET MVC中的学习,使用代码优先的数据库创建。

我有两节课:

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }
    public int Standard { get; set; }            
    public int SubjectId { get; set; }    

    [ForeignKey("SubjectId")]
    public ICollection<Subject> Subjects { get; set; }
}

public class Subject
{
    [Key]
    public int SubjectId{ get; set; }
    public string SubjectName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试向表中插入一条Student记录Student,该记录具有SubjectId引用该Subject表的外键。

我正在尝试两种可能的方法:

第一种方法

using(var cxt = new SchoolContext()) …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework ef-code-first-mapping

9
推荐指数
1
解决办法
1万
查看次数

如何在Entity Framework Core中设置实体关系

这里我们在EF Core上有3个表:

  1. 新闻
  2. 项目
  3. 链接

还有更多(新闻,项目除外):内容,帖子,表格等

和我的模型定义

public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public Link Link { get; set; }
}

public class News
{
    public int Id { get; set; }
    public string Header { get; set; }
    public string Content { get; set; }
    public Link Link { get; set; }
}

public class Link
{
    public int Id …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework-core .net-core asp.net-core ef-code-first-mapping

8
推荐指数
1
解决办法
438
查看次数

asp.net core 在两列上创建约束,其中一列是另一个实体

我有 2 个类(实体)Exemption 和 Period,我想使用来自豁免的 IdNumber 和来自 Period 的 Id 创建一个唯一索引

     public class Exemption
        {
            [Key]
            public int Id { get; set; }
            [Required]
            public string FirstName { get; set; }
            .
            .
            .
            [Required]
            public string IdNumber { get; set; }
            [Required]
            public Period Period { get; set; }
         }

     public class Period
        {
            [Key]
            public int Id { get; set; }
            .
            .
            .
            [Required]
            public string Year { get; set; }

         }
Run Code Online (Sandbox Code Playgroud)

使用 Fluent API 我在OnModelCreating …

.net entity-framework ef-code-first asp.net-core ef-code-first-mapping

5
推荐指数
1
解决办法
1709
查看次数

ASP.NET Core Entity Framework 代码到数据库脚手架无法识别 Id 属性或 [Key] 注释

我正在尝试为我的Ticket班级搭建一个剃刀页面集,当实体框架尝试创建数据库时出现错误:

这显示了我的“Ticket”定义旁边的错误,其中包括“Id”属性上方的 Key 注释

我的理解是,如果您有一个属性“Id”,它将使用它,并且如果您设置 [Key] 注释,它将专门告诉 Entity Framework 使用该属性。这两样东西我都有,那怎么办?

c# entity-framework-core ef-code-first-mapping entity-framework-migrations asp.net-core-scaffolding

2
推荐指数
1
解决办法
67
查看次数