0

Is there a way to ignore property from being mapped in runtime. Because I don't know if database has specific column and I have to check it before doing insert. If database doesn't have column then I want to ignore this one specific property.

UPDATE:

Here's my insert code

    public static void Insert(string connectionString, T entity)
    {
        using (var connection = new SqlConnection(connectionString))
        {
            connection.Open();

            connection.Insert(entity);
        }
    }
user2412672
  • 1,459
  • 3
  • 20
  • 36

1 Answers1

1

That Insert method is part of Dapper.Contrib, not Dapper itself. As the Readme for that library explains, you can use the [Write(false)] attribute to specify that a property isn't writeable, eg :

public class MyClass
{
    public int ID {get;set;}

    public DateTime Created{get;set;}

    [Write(false)]
    public DateTime CreatedDate =>Created.Date;

}

The source code shows that Dapper.Contrib simply ignores properties that aren't writable :

var properties = type.GetProperties().Where(IsWriteable).ToArray();

Dapper is a microORM, it doesn't offer the mapping features found in full ORMs like EF or NHibernate. Dapper.Contrib adds some helper methods and very basic mapping through 5 atrributes:

  • [Table("Tablename")] to specify the table name
  • [Key] to mark an auto-generated key field
  • [ExplicitKey] to mark a field that isn't generated automatically
  • [Write(true/false)] to mark (non)writable properties
  • [Computed] to mark calculated properties.

There's no way to specify a column name for example

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • But it means what I should you reflection to change [Write(true)] into [Write(false)] in runtime? – user2412672 Sep 11 '19 at 11:35
  • You asked how to exclude a property, not detect dynamically whether it exists and ignore it. Even full featured ORMs don't do that. If you use an ORM like EF or NH with a table that's missing a field you'll get an error. To do what you ask with EF you'd have to use [Fluent configuration](https://learn.microsoft.com/en-us/ef/core/modeling/included-properties#fluent-api), check the database schema on startup and add an `Ignore()` to the column config if you didn't find it. That's not what Dapper is for – Panagiotis Kanavos Sep 11 '19 at 11:41
  • @AmitJoshi Computed is ignored on updates only. Write means the property is ignored completely. If you check the source code you'll see that computed properties are handled while non-writeable properties are ignored completely – Panagiotis Kanavos Sep 11 '19 at 11:41
  • @PanagiotisKanavos: I did further research and updated my [answer](https://stackoverflow.com/a/57673976/5779732) accordingly. `Computed` attribute will also ignore the property while both `INSERT` as well as `UPDATE`. Please have a look and suggest if my tests were incorrect. – Amit Joshi Sep 11 '19 at 13:37