EF4 equivalent of NHibernate IUserType - nhibernate

I want to map a model property of type TimeZoneInfo to a column in the database. In NHib, I just made an IUserType "TimeZoneInfoString" that converted back and forth and then used a typedef. How can I do this type of work using Entity Framework 4.0?

Entity framework doesn't have equivalent to NHibernate's user types. You must create separate property in your entity for it and map only the string property. Somethink like:
public partial class MyEntity
{
public TimeZoneInfo TimeZone
{
get
{
return Parse(TimeZoneInfoString);
}
set
{
TimeZoneInfoString = value.ToString();
}
}
}
Where this class is your partial part to autogenerated entity. TimeZoneInfoString is property mapped in your entity and Parse and ToString contains your conversion logic.

Related

DDD ValueObject and Enumeration , is there any good way to implement serialization?

In DDD, Value Object and Enumeration are quite beautiful so that I want use both two in the daily program logic, not only domain logic. When use customized value objects and enumerations, serialization problem is coming : should I implemented all the value objects and enumeration with System.Text.Json.JsonConverter<T> , or is there any good way to handle serialization and deserialization ?
Update:
to make it clear, Eumeration demo as below(ValueObject derived classes are same.):
[JsonConverter(typeof(CustomizedConverter))]
public class CustomizedEnumeration1 : Enumeration
{
public string Customized { get; protected set; }
public ... // some other customized property or class
public CustomizedEnumeration(int id, string name, string customized) : base(id, string) {
Customized = customized;
}
}
public class Customized2 : Enumeration
{ ... }
public class OtherCustomized: Enumeration
{ ... }
In DDD, properties sometimes are sealed by protected/private setter, deserialization has no right to set the value. Many derived classes can't deserialize as expected, so we have to rewrite serialization with System.Text.Json.JsonConverter<T> one by one. rewrite every derived Enumeration / Valueobject converter is not good, can any one point out any easy abstraction for that ?
You can achieve your desired result. You need to switch to NewtonsoftJson serialization.
Call this in Startup.cs in the ConfigureServices method:
services.AddControllers().AddNewtonsoftJson();
After this, your constructor will be called by deserialization for classes with private setter.
There is no need for custom converters.
For reference, I am using ASP Net Core 3.1

Fluent NHibernate: the entity '(method name)' doesn't have an Id mapped.

This is my first time trying Fluent NHibernate and Auto mapping. Unfortunately I have run into an issue that I cannot get past. I'm getting an error saying that a method on one of my classes cannot be mapped.
public class Person
{
public IEnumerable<string> GetStuff(){return stuff;}
}
The Exception Message is:
The entity '<GetStuff>d__0' doesn't have an Id mapped.
I even tried adding an IAutoMappingOverride to ignore the method (using map.IgnoreProperty).
Is it really trying to map a method? whats going on here?
Every entity that you want to Automap must have an Id property, or inherit from a class that has an Id property. Your Person class does neither.
Also, in my experience, all public methods in entities must be declared virtual (though this may not be required if you eager load everything).
I got around this by manually marking each Entity with an interface.
public class MyAutomappingConfiguration : DefaultAutomappingConfiguration
{
public override bool ShouldMap(Type type)
{
return type.GetInterfaces().Contains(typeof (IEntity));
}
}

Why is prefix of underscore on public properties in my JSON result set

I use ASP.NET WCF to return .NET objects in JSON format through jquery calls.
When I changed my .NET classes to serializable, which I expose through methods in my WCF class, the objects property names suddenly changed from:
Name to _Name.
So all code in my javascript classes where I access json objects is wrong.
Why do the properties have a underscore prefix now?
And how do I change it back without removing the serializable attribute on the classes?
Thanks.
Christian
When you say that you "changed the class to serializable", does it mean you added the [Serializable] attribute on them? If this is the case: classes marked with that attribute have all of their fields serialized (no properties). In the example below, this class doesn't have any attributes, and it does have a parameter-less constructor, so it's considered a "POCO" (plain-old CLR object) type. POCO types have their public members (fields or properties) serialized. If you decorate it with [Serializable], then it will fall into the serializable rule.
Why do you need to mark your type with [Serializable]? If you really need to do that (for some legacy serializer), you can also decorate your type with [DataContract] and [DataMember] attributes, which are honored by the WCF serializer. You'd add [DataContract] on the type, and [DataMember] on the properties which you want serialized.
public class Person
{
private string _Name;
private int _Age;
public string Name {
get { return this._Name; }
set { this._Name = value; }
}
public string Age {
get { return this._Age; }
set { this._Age = value; }
}
}

How do I convert an object from Reflection to a generic collection?

I'm trying to write a Compare method to compare properties in some POCOs using Reflection to ensure that they've been persisted to the database correctly. For example, let's say I have this POCO:
public class NoahsArk
{
public string Owner { get; set; }
public ICollection<Animal> Animals { get; set; }
}
What I want to do is this:
[Test]
public class Saves_Correctly_To_Database()
{
var noahsArk = new NoahsArk { // some setup code here };
db.Save(noahsArk);
var dbNoahsArk = db.Get<NoahsArk>(noahsArk.Id);
Assert.That(Compare(noahsArk, dbNoahsArk), Is.True);
}
The ORM I'm using is NHibernate. My Compare method looks like this so far:
public static bool EqualsProperties<T>(this T x, T y)
{
var xType = x.GetType();
foreach (var property in xType.GetProperties())
{
if (property.GetValue(x, null).Implements(typeof(ICollection<>)))
{
var xValue = property.GetValue(x, null) as ICollection<T>;
var yValue = property.GetValue(y, null) as ICollection<T>;
}
Object.Implements() is an extension method I wrote to determine if a type implements an interface. As you can see, the method is incomplete. The problem I'm running into is that when I use property.GetValue(x, null), it returns an object, and I don't know how to cast it into its specific generic ICollection type. I need to be able to do this so I can use LINQ to do a x.Contains(y) to compare the two collections for equality. Any idea on how to do this?
P.S. I tried using Compare .NET Objects, but it's giving me a null reference exception somewhere deep within NHibernate. It doesn't properly handle how NHibernate proxies the ICollection for lazy loading. To make matters worse, NHibernate modifies the POCO to support lazy-loading, but this is all done at runtime. In the source code, it looks like you're just working with a regular ICollection, but NHibernate changes this to NHibernate.Collections.Generic.PersistentSet at runtime, and this is what's causing the comparer to fail.
Your question is a bit confusing because you don't need the type parameter T in the declaration of your EqualsProperties method. You just need
public static bool EqualsProperties(this object x, object y)
You then go on to use the same parameter T to cast properties of x and y to ICollection<T>; however, the objects in these collections obviously may have a different type than x and y.
Now to answer your question: you don't need to cast to the correct generic type to use the LINQ Contains method. You can do something like this:
xValue = property.GetValue(x, null);
yValue = property.GetValue(y, null);
if (typeof(IEnumerable).IsInstanceOf(x))
{
IEnumerable<object> xEnumerable = (x as IEnumerable).Cast<object>();
IEnumerable<object> yEnumerable = (y as IEnumerable).Cast<object>();
// use any LINQ method you like now
}
You should also make sure you use the LINQ overloads that take an equality comparer, as your domain objects obviously do not override the Equals method themselves. Otherwise you wouldn't be writing this unit testing code to compare them.
Sharp architecture framework use attribute to decor properties which should be taken into the equals method. See the source code of DomainSignatureAttribute class and EntityWithTypedId<>.Equals method.

nHibernate mapping to custom types

I have a Oracle database and one of the fields is a date range field. It is basically just stored in the database as a VARCHAR(40) in the format YYYY/MM/DD-YYYY/MM/DD. I want to map it in nHibernate to a custom class I have created like this
public class DateTimeRange
{
public DateTimeRange(DateTime fromTime, DateTime toTime)
{
FromTime = fromTime;
ToTime = toTime;
}
public override string ToString()
{
return String.Format("{0} to {1}", FromTime.ToString("HH:mm:ss"), ToTime.ToString("HH:mm:ss"));
}
public DateTime FromTime { get; set; }
public DateTime ToTime { get; set; }
}
How can I map to custom classes like this?
You need to implement your own IUserType.
See this blog post for details. I'll also paste the relevant section below in case the blog disappears.
In NHibernate, a custom mapping type is a class that derives from either the IUserType or ICompositeUserType interfaces. These interfaces contain several methods that must be implemented, but for our purposes here, we’re going to focus on 2 of them. Consider the following.
public class TypeClassUserType : IUserType
{
object IUserType.NullSafeGet(IDataReader rs,
string[] names,
object owner) {
string name = NHibernateUtil.String.NullSafeGet(rs,
names[0]) as string;
TypeClassFactory factory = new TypeClassFactory();
TypeClass typeobj = factory.GetTypeClass(name);
return typeobj;
}
void IUserType.NullSafeSet(IDbCommand cmd,
object value,
int index) {
string name = ((TypeClass)value).Name;
NHibernateUtil.String.NullSafeSet(cmd, name, index);
}
}
Having created this class, I can now explicitly map the association between ActualClass and TypeClass as a simple property on the ActualClass mapping.
<property
name="Type"
column="TypeName"
type="Samples.NHibernate.DataAccess.TypeClassUserType,
Samples.NHibernate.DataAccess" />
As NHibernate is in the process of saving an instance of ActualType, it will load and create a new instance of TypeClassUserType and call the NullSafeSet method. As you can see from the method body, I am simply extracting the name from the mapped property (passed in as the value parameter) and setting the extracted name as the value of the parameter to be set in the database. The net result is that although the Type property of ActualClass is TypeClass in the domain model, only the Name property of the TypeClass object gets stored in the database. The converse is also true. When NHibernate is loading an instance of ActualType from the database and the finds a property of my custom mapping type, it loads my custom type and calls the NullSafeGet method. As you can see, my method gets the name from the returned data, calls my flyweight factory to get the correct instance of TypeClass, and then actually returns that instance. The type resolution process happens transparently to my data access classes (and even to NHibernate itself for that matter).