忽略模型属性的属性

时间:2013-10-31 21:04:06

标签: dapper dapper-rainbow dapper-extensions

如何使用dapper / dapper extensions / dapper rainbow或任何

忽略模型上的属性

那些精致的图书馆?

5 个答案:

答案 0 :(得分:21)

Dapper.Contrib内置支持将列标记为计算:add ComputedAttribute to allow support for computed columns on Insert。以下是它的工作原理:

class MyModel
{
  public string Property1 { get; set; }

  [Computed]
  public int ComputedProperty { get; set; }
}

在插入时将忽略标有Computed属性的属性。

答案 1 :(得分:9)

Dapper创作者Sam Saffron针对另一个SO用户的问题here解决了这一要求。看看吧。

另外,如果你想使用Sam在答案中提到的Dapper Extensions library,你可以从Github或Nuget获得它。

以下是忽略图书馆Test Project中的属性的示例。

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();
        }
    }
}

答案 2 :(得分:8)

就我而言,我使用了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; }
}

答案 3 :(得分:4)

您可以设计一个没有computed属性的基类,并将其用于插入。

  class BasePerson
    {
      public String Name {get;set;}
    }

    class Person: BasePerson
    {
     public String ComputedProperty {get;set;}
    }

    Insert<BasePerson>(person);

答案 4 :(得分:2)

对于那些不想包含DapperExtensions的人,也可以使用标准DatabaseGenerated中的System.ComponentModel.DataAnnotations.Schema

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]