DapperLib / DapperLib/Dapper

CustomTypeHandler seems to doesn't work correctly

Open
#934 12 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

area:typehandlers
Dominant language
C#
Stars
18.4k
Forks
3.7k
Avg merge
5h 8m
Merged PRs (30d)
1

Description

I have an entity like this:

[Table("Entity", Schema = "dbo")]
internal class Entity
{
    [Key]
    public virtual int Id { get; set; }
    public virtual CustomType Filters { get; set; }
    public virtual string Name { get; set; }
    ...
}

and custom type like this:

[JsonObject]
public class CustomType
{
    [JsonProperty(PropertyName = "a")]public string a{ get; set; }
    [JsonProperty(PropertyName = "b")]public string b { get; set; }
    [JsonProperty(PropertyName = "d")]public IReadOnlyCollection<d> d{ get; set; }
}

custom handler like this:

public class JsonTypeHandler<CustomType> : SqlMapper.TypeHandler<CustomType>
{
    public override void SetValue(IDbDataParameter parameter, CustomType value)
    {
        parameter.Value = value == null
            ? (object) DBNull.Value
            : JsonConvert.SerializeObject(value);
        parameter.DbType = DbType.String;
    }

    public override CustomType Parse(object value)
    {
        return JsonConvert.DeserializeObject<CustomType>(value.ToString());
    }
}

and I register it in global.asax.cs like this:

SqlMapper.AddTypeHandler(new JsonTypeHandler<CustomType>());

The problem is that SetValue is not invoked when Execute is called. I'm using a Dapper.FastCrud, and my code to insert an entity to db looks like this:

var entity = new Entity
{
    Filters = new CustomType{bla bla},
    Name = "fafsd",
    ...
};

_dbConnection.Insert(dataExtractEntry, x => x.AttachToTransaction(tx));

Is there something more I have to do here?

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the JsonTypeHandler registration in global.asax.cs and the Dapper.FastCrud Insert call shown in the issue. Reproduce the insert and trace whether SetValue is reached for Entity.Filters; done means the custom handler is invoked and the CustomType value is persisted correctly.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
database
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.