Hello everyone,
Is there a way to use User-Defined Types (CLR), successfully deployed and published to test database, in Entity Framework and if yes how to do that?
Bellow, you could find definition ofUser-Defined Types (CLR) UDTEmail.cs file and it issuccessfully published in test database.
However, when I add ADO.NET Entity Data Model and choose test database I get next error:
Error 6005: The data type 'UDTEmail' is currently not supported for the target Entity Framework version; the column 'EmailCol' in the table 'Test.dbo.Test' was excluded.
How to make EF work with UDT CLR?
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
using Microsoft.SqlServer.Server;
using System.Text.RegularExpressions;
[Serializable]
[Microsoft.SqlServer.Server.SqlUserDefinedType(Format.UserDefined, MaxByteSize = 256)]
public struct UDTEmail : INullable, IBinarySerialize
{
private string m_local_part;
private string m_domain;
private string m_tld;
private bool m_Null;
// Property atributa
public string M_local_part
{
get
{
return (this.m_local_part);
}
set
{
this.m_local_part = value;
this.m_Null = false;
}
}
public string M_domain
{
get
{
return (this.m_domain);
}
set
{
this.m_domain = value;
this.m_Null = false;
}
}
public string M_tld
{
get
{
return (this.m_tld);
}
set
{
this.m_tld = value;
this.m_Null = false;
}
}
public bool IsNull
{
get
{
// Put your code here
return m_Null;
}
}
public static UDTEmail Null
{
get
{
UDTEmail h = new UDTEmail();
h.m_Null = true;
return h;
}
}
// metode
public override string ToString()
{
return m_local_part + "@" + m_domain + '.' + m_tld;
}
public static UDTEmail Parse(SqlString s)
{
if (s.IsNull | s.Value.Length == 0) return Null;
if (!IsValid(s)) return Null;
UDTEmail udt = new UDTEmail();
int at_pos = s.Value.IndexOf('@');
int period_pos = s.Value.LastIndexOf('.');
udt.m_local_part = s.Value.Substring(0, at_pos);
udt.m_domain = s.Value.Substring(at_pos + 1, period_pos - at_pos - 1);
udt.m_tld = s.Value.Substring(period_pos + 1,
s.Value.Length - period_pos - 1);
return udt;
}
private static bool IsValid(SqlString s)
{
return Regex.IsMatch(s.Value,
@"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
@"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
}
public void Read(BinaryReader r)
{
m_Null = r.ReadBoolean();
if (!m_Null)
{
m_local_part = r.ReadString();
m_domain = r.ReadString();
m_tld = r.ReadString();
}
}
public void Write(BinaryWriter w)
{
w.Write(m_Null);
if (!m_Null)
{
w.Write(m_local_part);
w.Write(m_domain);
w.Write(m_tld);
}
}
}