还在学EF Core
,看到微软官网文档有写,就想尝试写一写,但我的会报错。
微软文档\EF Core\创建模型\关系
项目环境 | 版本信息 | 备注 |
---|---|---|
NET | 6.x | |
EF Core | 3.x | running |
EF | 6 | 项目也同时具有这个,但非running 状态 |
下面是我写的模型
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ApiDB.Model
{
public class Blogs
{
[Key, Column("bId"), DatabaseGenerated(DatabaseGeneratedOption.Identity)]//文章Id
public int bId { set; get; }
[Column(name: "bTitle",TypeName ="varchar(25)")]//文章名
public string? bTitle { set; get; }
[Column(name: "bText"), Required]//内容
public string? bDescription { set; get; }
[Column("bCreated")]//创建时间
public DateTime created
{
set
{
created = DateTime.Now;
}
get
{
return this.created;
}
}
[Column("bRead")]//阅读量
public int read { set; get; }
public Parts Parts { get; set; } //引用导航
[Column("name")]
public int uuName { set; get; } //作者Id
}
}
// 博文模型 ---关联--> 角色模型
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ApiDB.Model
{
// 角色模型
[Table("Parts")]
public class Parts
{
[Key,Column("uuId")]
public int Id { set; get; }
[Column("uuName"), MaxLength(255)]
public string? Name { set; get; }
[Column("uuStatus"), Precision(3)]
public int Status { set; get; }
[Column("uuPass"), MaxLength(255)]
public string? Pass { set; get; }
public List Blog { set; get; }//导航
}
}
生成SQL
语句:
SELECT `b`.`bId`, `b`.`PartsId`, `b`.`bText`, `b`.`bTitle`, `b`.`bCreated`, `b`.`bRead`, `b`.`name` FROM `Blog` AS `b`
其中关于
b.PartsId
这个字段我不明白为什么会存在,是因为映射导航的原因吗?所以生成了一个未知的字段?
根据上面Parts
模型可以知道我的数据库对应表使用的是uuId
这个字段。所以这个字段应该怎么修改才能正常关联起来呢?对于我的
Blog
表的name
字段,它是一个外键,所以我希望能通过数据注释
的形式标写出来
能实现关系型模型关联,或者正常读取Blog
模型
现在我尝试修改了Blog
模型,为public Parts Parts { get; set; } //引用导航
添加了数据注释[ForeignKey("Name")]
,并将uuName
字段修改为Name
了。
这时候生成 SQL
为:
SELECT `b`.`bId`, `b`.`name`, `b`.`bText`, `b`.`bTitle`, `b`.`bCreated`, `b`.`bRead` FROM `Blog` AS `b`
终端报错为:An exception occurred while iterating over the results of a query for context type 'ApiDB.Comon.WebContext'. System.FormatException: Input string was not in a correct format.
这个又是什么问题?