我搭建了.net core 的三层架构项目,定义了一个接口接收postman传递的json数据实现新建数据表的功能
实体层:
public class FWTB
{
[Key]
public int Id { get; set; }
public class Database
{
[Key]
public int Id { get; set; }
public string Databases { get; set; }
}
public class Constraints
{
[Key]
public int Id { get; set; }
public string Relation { get; set; }
}
public class Structure
{
[Key]
public int Id { get; set; }
public string StoredProcedures { get; set; }
public string View { get; set; }
public string Index { get; set; }
public string PrimayKey { get; set; }
public string Triggers { get; set; }
}
public class Tables
{
[Key]
public int Id { get; set; }
public string Table { get; set; }
public Constraints Constraints { get; set; }
public Structure Structure { get; set; }
}
public class Db
{
[Key]
public int Id { get; set; }
public Database Databse { get; set; }
public List<Tables> Tables { get; set; }
}
public Db db { get; set; }
}
控制器层:
public async Task<IActionResult> AddTableInvent([FromBody] FWTB fWTB)
{
// 将 JObject 转换为实体对象
// var fWTBDto = JsonConvert.DeserializeObject<FWTBDto>(data.ToString());
await _tableInventService.AddTableInvent(fWTB);
return Ok();
}
json数据:
{
"Id":1,
"db": {
"Id": 2,
"databse": {
"Id": 3,
"databases": "fwt-db"
},
"tables": [
{
"Id": 4,
"table": "数据表1:fwt-tb00",
"constraints": {
"Id": 5,
"Relation": "关系:主外键"
},
"structure": {
"Id": 6,
"storedProcedures": "存储过程:pro-fwt-tb00",
"view": "FWT_BY",
"Index": "索引:priindex",
"PrimayKey": "主键:id",
"triggers": "trigger_FWT"
}
}
]
}
}
实现服务层:
public async Task AddTableInvent(FWTB fWTB)
{
await _tableInventRepository.AddTableInvent(fWTB);
}
存储层:
public async Task AddTableInvent(FWTB fWTB)
{
await _mydbContext.FWTB.AddAsync(fWTB);
await _mydbContext.SaveChangesAsync();
}
我发送请求的时候提示:
System.InvalidOperationException: Unable to track an instance of type 'FWTB' because it does not have a primary key. Only entity types with primary keys may be tracked.
说我没有定义主键值,但是我明明定义了主键。