2013-10-31 52 views
13

如何忽略我的模型上使用精簡/精細擴展/精靈彩虹或任何忽略模型屬性上的屬性

那些精簡庫?

+0

對於什麼CRUD操作? – Alex

+0

For Insert (person)。人有一種計算性質。哪些不屬於數據庫。 – Elisabeth

+1

由於以下答案中沒有提供基於Dapper.Rainbow的項目的解決方案,因此我添加了此評論。 Dapper Rainbow有一個可以使用的IgnoreProperty屬性。您的POCO類必須引用Dapper.Rainbow。{SQL},然後您可以使用[IgnoreProperty(true)]來排除您希望排除的屬性 –

回答

8

小巧玲瓏的創作者薩姆藏紅花響應另一個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(); 
     } 
    } 
} 
+1

Where /何時實例化PersonMapper類? Dapper擴展是通過使用entityname +「Mapper」字符串並試圖實例化它來查找Mapper類的? – Elisabeth

+2

是的,我相信Dapper Extensions的AutoMapper功能尋找單一的實體名稱+「Mapper」後綴來自動映射字段忽略,不同名稱的字段等。換句話說,我認爲(沒有嘗試過),你應該沒問題只需定義此PersonMapper類並忽略要從POCO忽略的字段。請參閱這裏的文檔:https://github.com/tmsmith/Dapper-Extensions/wiki/AutoClassMapper – Shiva

+0

很好,它爲我工作。我的XXXMapper類具有相同的名稱空間。 – Elisabeth

3

您可以設計一個沒有計算屬性的基類並將其用於插入。

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

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

    Insert<BasePerson>(person); 
12

Dapper.Contrib內置用於標記計算列:add ComputedAttribute to allow support for computed columns on Insert。下面是它如何工作的:標有Computed屬性

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

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

屬性將在插入被忽略。

+0

還有'[Write(false)]'屬性。任何人都可以告訴'[Computed]'和'[Write(false)]'之間有什麼區別嗎? – vaheeds

+1

@vaheeds我最好的猜測是,他們是在不同的時間被不同的人添加的,他們可能沒有意識到另一個人。我添加了'Computed'屬性,並且當時沒有意識到任何'Write'屬性。 –

3

在我的情況下,我用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; } 
} 
1

對於那些不希望包括DapperExtensions,DatabaseGenerated從標準System.ComponentModel.DataAnnotations.Schema也可以使用。

[DatabaseGenerated(DatabaseGeneratedOption.Computed)] 
+0

此解決方案不適用於.NET核心上的Dapper 1.50.2 –