谈谈c# partial class的实际巧妙场景
2022-09-09 本文已影响0人
吉凶以情迁
partial class
就是将一个类的代码内容放到任意地方可以多份,看上去鸡肋实际上还是有点用处的
假设有一个类 是自动生成的 ,比如上一篇文章的脚手架, 是根据数据库自动生成,而且将来加数据我可能需要再次自动生成 ,会覆盖数据,但是这个类有些字段我不需要在数据库里面映射,但是返回给前端序列化则需要,那么怎么办呢?
新建一个cs文件,放在其他地方 但是 里面的命名空间和类名一致partial
修饰,完美。
namespace CoreWebApi_.Models
{
public partial class Node
{
public List<View> view3ds { get; set; }
public string? Name { get; set; }
public string? Descript { get; set; }
public string? Tag { get; set; }
public int Id { get; set; }
public int ParentId { get; set; }
public int? Flag { get; set; }
}
}
另外一部分非自动生成
using Newtonsoft.Json;
namespace CoreWebApi_.Models
{
public partial class Node
{
public string? ItemName { get; set; }
[System.ComponentModel.DataAnnotations.Schema.NotMapped]
public string? ItemDescript { get; set; }
[JsonIgnore]
[System.ComponentModel.DataAnnotations.Schema.NotMapped]
public List<Node> items;
[System.ComponentModel.DataAnnotations.Schema.NotMapped]
public List<View> views;
[System.ComponentModel.DataAnnotations.Schema.NotMapped]
[JsonIgnore]
public Node parentNode;
[System.ComponentModel.DataAnnotations.Schema.NotMapped]
List<View> view3Ds;
}
}