我该如何使用dapper/dapper扩展/dapper rainbow等dapper库忽略我的模型属性?
Dapper.Contrib内置了支持将列标记为计算列的功能:添加ComputedAttribute以允许在插入时支持计算列。以下是它的工作原理:
class MyModel
{
public string Property1 { get; set; }
[Computed]
public int ComputedProperty { get; set; }
}
标有Computed
属性的属性将在插入时被忽略。
Computed
attribute will be ignored during insertion.[Write(false)]
属性。有人能告诉我[Computed]
和[Write(false)]
之间的区别吗? - vaheedsDapper的创建者Sam Saffron已回答了另一个SO用户的问题,您可以在这里查看。
此外,如果您想使用Sam在答案中提到的Dapper Extensions库,您可以从Github或Nuget获取它。
下面是一个忽略库中属性的示例测试项目。
using System;
using System.Collections.Generic;
using DapperExtensions.Mapper;
namespace DapperExtensions.Test.Data
{
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateCreated { get; set; }
public bool Active { get; set; }
public IEnumerable<Phone> Phones { get; private set; }
}
public class Phone
{
public int Id { get; set; }
public string Value { get; set; }
}
public class PersonMapper : ClassMapper<Person>
{
public PersonMapper()
{
Table("Person");
Map(m => m.Phones).Ignore();
AutoMap();
}
}
}
Dapper.Contrib
。[Write(false)]
特性应该可以解决这个问题。
有些人建议使用[Computed]
特性。public class Person
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
[Write(false)]
public IEnumerable<Email> Emails { get; }
}
对于不想包含DapperExtensions的人来说,也可以使用标准的System.ComponentModel.DataAnnotations.Schema
中的DatabaseGenerated
。
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
class BasePerson
{
public String Name {get;set;}
}
class Person: BasePerson
{
public String ComputedProperty {get;set;}
}
Insert<BasePerson>(person);