[英]EF Core 7.0 Json column type and entity configuration
I would like to arrange new feature which is Json column types in EF Core 7.0 but i am not sure how to make entity configuration ( https://www.npgsql.org/efcore/mapping/json.html?tabs=fluent-api%2Cpoco )我想在 EF Core 7.0 中安排新功能,即 Json 列类型,但我不确定如何进行实体配置( https://www.npgsql.org/efcore/mapping/json.html?tabs=fluent-api %2Cpoco )
For example, I have a class:例如,我有一个类:
public class Entity
{
public Guid Id { get; set; }
public bool Deleted { get; set; }
public string Name { get; set; }
public DateTime Date { get; set; }
}
I would like to create table which looks like this: Columns: Id (Guid), Deleted (bool), Data (json string)我想创建如下所示的表: Columns: Id (Guid), Deleted (bool), Data (json string)
Data in json column should look like: json 列中的数据应如下所示:
{
"Id": "00000000-0000-0000-0000-000000000000",
"Deleted": false,
"Name": "Example name",
"Date": "2022-12-20T22:07:17Z"
}
How can i configure entity to get expected result?如何配置实体以获得预期结果?
You can configure your models like this,你可以像这样配置你的模型,
DataEntity.cs数据实体.cs
public class DataEntity
{
public Guid Id { get; set; }
public bool Deleted { get; set; }
public string Name { get; set; }
public DateTime Date { get; set; }
}
OwnerEntity.cs所有者实体.cs
public class OwnerEntity
{
public Guid Id { get; set; }
public bool Deleted { get; set; }
public DataEntity Data { get; set; }
}
Now the key part is in your model configs,现在关键部分在你的模型配置中,
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<OwnerEntity>().OwnsOne(
owner => owner.Data, ownedNavigationBuilder =>
{
ownedNavigationBuilder.ToJson();
});
}
After you run the Add-Migration
command, you should see the migration script like this,运行Add-Migration
命令后,您应该会看到这样的迁移脚本,
migrationBuilder.CreateTable(
name: "OwnerEntities",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Deleted = table.Column<bool>(type: "bit", nullable: false),
Data = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_OwnerEntities", x => x.Id);
});
Note that the Data column is string
type.请注意,Data 列是string
类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.