mirror of
https://github.com/dotnetcore/FreeSql.git
synced 2026-02-09 09:50:54 +08:00
update
33
骚操作.md
33
骚操作.md
@@ -286,25 +286,42 @@ var sql1 = fsql.Select<SysModule>()
|
|||||||
|
|
||||||
# 12、自定义实体特性、与其他 ORM 共用特性
|
# 12、自定义实体特性、与其他 ORM 共用特性
|
||||||
|
|
||||||
抛砖引玉,以下的示例代码,FreeSql 使用 EFCore 的实体特性:
|
本功能可实现与其他 ORM 使用一套 Attribute,避免维护两份实体特性的烦恼:
|
||||||
|
|
||||||
|
> v1.4.0+ 已自动识别 EFCore 实体特性 Key/Required/NotMapped/Table/Column
|
||||||
|
|
||||||
```csharp
|
```csharp
|
||||||
fsql.Aop.ConfigEntity += (s, e) => {
|
fsql.Aop.ConfigEntity += (s, e) => {
|
||||||
var attr = e.EntityType.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.Schema.TableAttribute), false).FirstOrDefault() as System.ComponentModel.DataAnnotations.Schema.TableAttribute;
|
var attr = e.EntityType.GetCustomAttributes(typeof(MyTableAttribute), false).FirstOrDefault() as MyTableAttribute;
|
||||||
if (attr != null)
|
if (attr != null)
|
||||||
e.ModifyResult.Name = attr.Name; //表名
|
e.ModifyResult.Name = attr.Name; //表名
|
||||||
};
|
};
|
||||||
fsql.Aop.ConfigEntityProperty += (s, e) => {
|
fsql.Aop.ConfigEntityProperty += (s, e) => {
|
||||||
if (e.Property.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.KeyAttribute), false).Any())
|
var attr = e.Property.GetCustomAttributes(typeof(MyColumnAttribute), false).FirstOrDefault() as MyColumnAttribute;
|
||||||
e.ModifyResult.IsPrimary = true; //主键
|
if (attr != null)
|
||||||
|
e.ModifyResult.Name = attr.Name; //字段名
|
||||||
};
|
};
|
||||||
|
|
||||||
[System.ComponentModel.DataAnnotations.Schema.Table("xxx")]
|
[MyTable("xxx")]
|
||||||
class ModelAopConfigEntity {
|
class YourEntity {
|
||||||
[System.ComponentModel.DataAnnotations.Key]
|
[MyColumn("id")]
|
||||||
[Column(IsPrimary = false)]
|
|
||||||
public int pkid { get; set; }
|
public int pkid { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class MyTableAttribute : Attribute {
|
||||||
|
public string Name { get; }
|
||||||
|
public MyTableAttribute(string name)
|
||||||
|
{
|
||||||
|
this.Name = name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class MyColumnAttribute : Attribute {
|
||||||
|
public string Name { get; }
|
||||||
|
public MyColumnAttribute(string name)
|
||||||
|
{
|
||||||
|
this.Name = name;
|
||||||
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
Reference in New Issue
Block a user