使用.NET core 2.0和实体框架将JSON数据插入到postgres中 [英] Insert JSON data into postgres using .NET core 2.0 and entity framework

查看:137
本文介绍了使用.NET core 2.0和实体框架将JSON数据插入到postgres中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是PostgreSQL数据库的新手,我们正在尝试使用.NET Core 2.0 api实现端点将JSON数据保存到PostgreSQL数据库



< b> #PostgreSQL表定义:

ID - UUID

DeptId - int4

DeptSettings - json



任何人都可以分享一个代码示例,使用.NET Core / C#中的Entity Framework将json数据保存到PostgreSQL吗?



提前谢谢。



我尝试过:



无法通过互联网找到相同的解决方案。从此以后,扩展到更广泛的论坛。

解决方案

Json类型映射到.Net中的字符串。因此,在实体模型中将 DeptSettings 定义为 string

  public   class 部门{
public Guid ID { get ; set ; }
public int DeptId { get ; set ; }
public string DeptSettings { get ; set ; }
}



在ApplicationDbContext文件中,通过将以下内容添加到模型的OnModelCreating中来显式指定PostgreSQL数据类型:

< pre lang =c#> protected 覆盖 void OnModelCreating(ModelBuilder构建器){
builder.Entity< Department>()。Property(d = > d.DeptSettings).HasColumnType( json);
}



这样,字符串将被转换为json并存储在数据库中。



注意:DeptSettings的值必须是一个字符串。


I am a newbie to PostgreSQL db and we're trying to implement an endpoint to save JSON data to PostgreSQL DB using the .NET Core 2.0 api's

# PostgreSQL Table Definition:
ID - UUID
DeptId - int4
DeptSettings - json

Can anyone please share a code sample to save json data to PostgreSQL using Entity Framework in .NET Core/C#?

Thank you in advance.

What I have tried:

Unable to find any solution for the same over internet. Henceforth, reaching out to broader forum.

解决方案

Json type is mapped to string in .Net. So, define DeptSettings as string in entity model.

public class Department {
  public Guid Id { get; set; }
  public int DeptId { get; set; }
  public string DeptSettings { get; set; }
}


In the ApplicationDbContext file, explicitly specify the PostgreSQL data type by adding the following to your model's OnModelCreating:

protected override void OnModelCreating(ModelBuilder builder) {
  builder.Entity<Department>().Property(d => d.DeptSettings).HasColumnType("json");
}


This way, the string will be cast to json and stored in the database.

Note: The value of the DeptSettings must be a string.


这篇关于使用.NET core 2.0和实体框架将JSON数据插入到postgres中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆