Last active
November 28, 2022 14:50
-
-
Save pwelter34/827f6a33957a31f18f4eb92d8141e23d to your computer and use it in GitHub Desktop.
ConcurrencyToken
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public readonly struct ConcurrencyToken : IEquatable<ConcurrencyToken> | |
{ | |
public static readonly ConcurrencyToken None = new(Array.Empty<byte>()); | |
public byte[] Value { get; } | |
public ConcurrencyToken(byte[] value) | |
{ | |
Value = value ?? Array.Empty<byte>(); | |
} | |
public ConcurrencyToken(string value) | |
{ | |
Value = string.IsNullOrEmpty(value) ? Array.Empty<byte>() : Convert.FromHexString(value); | |
} | |
public override string ToString() | |
{ | |
return Value != null ? Convert.ToHexString(Value) : null; | |
} | |
public override bool Equals(object obj) | |
{ | |
return obj is ConcurrencyToken token && Equals(token); | |
} | |
public bool Equals(ConcurrencyToken other) | |
{ | |
return EqualityComparer<byte[]>.Default.Equals(Value, other.Value); | |
} | |
public override int GetHashCode() | |
{ | |
return Value.GetHashCode(); | |
} | |
public static implicit operator byte[](ConcurrencyToken token) => token.Value; | |
public static implicit operator string(ConcurrencyToken token) => token.ToString(); | |
public static implicit operator ConcurrencyToken(byte[] token) => new(token); | |
public static implicit operator ConcurrencyToken(string token) => new(token); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ConcurrencyTokenTypeHandler : SqlMapper.TypeHandler<ConcurrencyToken> | |
{ | |
public override ConcurrencyToken Parse(object value) | |
{ | |
if (value is string textToken) | |
return new ConcurrencyToken(textToken); | |
if (value is byte[] byteToken) | |
return new ConcurrencyToken(byteToken); | |
return ConcurrencyToken.None; | |
} | |
public override void SetValue(IDbDataParameter parameter, ConcurrencyToken value) | |
{ | |
parameter.Value = value.Value; | |
parameter.DbType = DbType.Binary; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment