Search Results

Search found 11 results on 1 pages for 'iusertype'.

Page 1/1 | 1 

  • NHibernate IUserType convert nullable DateTime to DB not-null value

    - by barakbbn
    I have legacy DB that store dates that means no-date as 9999-21-31, The column Till_Date is of type DateTime not-null="true". in the application i want to build persisted class that represent no-date as null, So i used nullable DateTime in C# //public DateTime? TillDate {get; set; } I created IUserType that knows to convert the entity null value to DB 9999-12-31 but it seems that NHibernate doesn't call SafeNullGet, SafeNullSet on my IUserType when the entity value is null, and report a null is used for not-null column. I tried to by-pass it by mapping the column as not-null="false" (changed only the mapping file, not the DB) but it still didn't help, only now it tries to insert the null value to the DB and get ADOException. Any knowledge if NHibernate doesn't support IUseType that convert null to not-null values? Thanks //Implementation public class NullableDateTimeToNotNullUserType : IUserType { private static readonly DateTime MaxDate = new DateTime(9999, 12, 31); public new bool Equals(object x, object y) { //This didn't work as well if (ReferenceEquals(x, y)) return true; //if(x == null && y == null) return false; if (x == null || y == null) return false; return x.Equals(y); } public int GetHashCode(object x) { return x == null ? 0 : x.GetHashCode(); } public object NullSafeGet(IDataReader rs, string[] names, object owner) { var value = rs.GetDateTime(rs.GetOrdinal(names[0])); return (value == MaxDate)? null : value; } public void NullSafeSet(IDbCommand cmd, object value, int index) { var dateValue = (DateTime?)value; var dbValue = (dateValue.HasValue) ? dateValue.Value : MaxDate; ((IDataParameter)cmd.Parameters[index]).Value = dbValue; } public object DeepCopy(object value) { return value; } public object Replace(object original, object target, object owner) { return original; } public object Assemble(object cached, object owner) { return cached; } public object Disassemble(object value) { return value; } public SqlType[] SqlTypes { get { return new[] { NHibernateUtil.DateTime.SqlType }; } } public Type ReturnedType { get { return typeof(DateTime?); } } public bool IsMutable { get { return false; } } } } //Final Implementation with fixes. make the column mapping in hbm.xml not-null="false" public class NullableDateTimeToNotNullUserType : IUserType { private static readonly DateTime MaxDate = new DateTime(9999, 12, 31); public new bool Equals(object x, object y) { //This didn't work as well if (ReferenceEquals(x, y)) return true; //if(x == null && y == null) return false; if (x == null || y == null) return false; return x.Equals(y); } public int GetHashCode(object x) { return x == null ? 0 : x.GetHashCode(); } public object NullSafeGet(IDataReader rs, string[] names, object owner) { var value = NHibernateUtil.Date.NullSafeGet(rs, names[0]); return (value == MaxDate)? default(DateTime?) : value; } public void NullSafeSet(IDbCommand cmd, object value, int index) { var dateValue = (DateTime?)value; var dbValue = (dateValue.HasValue) ? dateValue.Value : MaxDate; NHibernateUtil.Date.NullSafeSet(cmd, valueToSet, index); } public object DeepCopy(object value) { return value; } public object Replace(object original, object target, object owner) { return original; } public object Assemble(object cached, object owner) { return cached; } public object Disassemble(object value) { return value; } public SqlType[] SqlTypes { get { return new[] { NHibernateUtil.DateTime.SqlType }; } } public Type ReturnedType { get { return typeof(DateTime?); } } public bool IsMutable { get { return false; } } } }

    Read the article

  • How do you map a DateTime property to 2 varchar columns in the database with NHibernate (Fluent)?

    - by gabe
    I'm dealing with a legacy database that has date and time fields as char(8) columns (formatted yyyyMMdd and HH:mm:ss, respectively) in some of the tables. How can i map the 2 char columns to a single .NET DateTime property? I have tried the following, but i get a "can't access setter" error of course because DateTime Date and TimeOfDay properties are read-only: public class SweetPocoMannaFromHeaven { public virtual DateTime? FileCreationDateTime { get; set; } } . mapping.Component<DateTime?>(x => x.FileCreationDateTime, dt => { dt.Map(x => x.Value.Date, "file_creation_date"); dt.Map(x => x.Value.TimeOfDay, "file_creation_time"); }); I have also tried defining a IUserType for DateTime, but i can't figure it out. I've done a ton of googling for an answer, but i can't figure it out still. What is my best option to handle this stupid legacy database convention? A code example would be helpful since there's not much out for documentation on some of these more obscure scenarios.

    Read the article

  • NHibernate Pitfalls: Custom Types and Detecting Changes

    - by Ricardo Peres
    This is part of a series of posts about NHibernate Pitfalls. See the entire collection here. NHibernate supports the declaration of properties of user-defined types, that is, not entities, collections or primitive types. These are used for mapping a database columns, of any type, into a different type, which may not even be an entity; think, for example, of a custom user type that converts a BLOB column into an Image. User types must implement interface NHibernate.UserTypes.IUserType. This interface specifies an Equals method that is used for comparing two instances of the user type. If this method returns false, the entity is marked as dirty, and, when the session is flushed, will trigger an UPDATE. So, in your custom user type, you must implement this carefully so that it is not mistakenly considered changed. For example, you can cache the original column value inside of it, and compare it with the one in the other instance. Let’s see an example implementation of a custom user type that converts a Byte[] from a BLOB column into an Image: 1: [Serializable] 2: public sealed class ImageUserType : IUserType 3: { 4: private Byte[] data = null; 5: 6: public ImageUserType() 7: { 8: this.ImageFormat = ImageFormat.Png; 9: } 10: 11: public ImageFormat ImageFormat 12: { 13: get; 14: set; 15: } 16: 17: public Boolean IsMutable 18: { 19: get 20: { 21: return (true); 22: } 23: } 24: 25: public Object Assemble(Object cached, Object owner) 26: { 27: return (cached); 28: } 29: 30: public Object DeepCopy(Object value) 31: { 32: return (value); 33: } 34: 35: public Object Disassemble(Object value) 36: { 37: return (value); 38: } 39: 40: public new Boolean Equals(Object x, Object y) 41: { 42: return (Object.Equals(x, y)); 43: } 44: 45: public Int32 GetHashCode(Object x) 46: { 47: return ((x != null) ? x.GetHashCode() : 0); 48: } 49: 50: public override Int32 GetHashCode() 51: { 52: return ((this.data != null) ? this.data.GetHashCode() : 0); 53: } 54: 55: public override Boolean Equals(Object obj) 56: { 57: ImageUserType other = obj as ImageUserType; 58: 59: if (other == null) 60: { 61: return (false); 62: } 63: 64: if (Object.ReferenceEquals(this, other) == true) 65: { 66: return (true); 67: } 68: 69: return (this.data.SequenceEqual(other.data)); 70: } 71: 72: public Object NullSafeGet(IDataReader rs, String[] names, Object owner) 73: { 74: Int32 index = rs.GetOrdinal(names[0]); 75: Byte[] data = rs.GetValue(index) as Byte[]; 76: 77: this.data = data as Byte[]; 78: 79: if (data == null) 80: { 81: return (null); 82: } 83: 84: using (MemoryStream stream = new MemoryStream(this.data ?? new Byte[0])) 85: { 86: return (Image.FromStream(stream)); 87: } 88: } 89: 90: public void NullSafeSet(IDbCommand cmd, Object value, Int32 index) 91: { 92: if (value != null) 93: { 94: Image data = value as Image; 95: 96: using (MemoryStream stream = new MemoryStream()) 97: { 98: data.Save(stream, this.ImageFormat); 99: value = stream.ToArray(); 100: } 101: } 102: 103: (cmd.Parameters[index] as DbParameter).Value = value ?? DBNull.Value; 104: } 105: 106: public Object Replace(Object original, Object target, Object owner) 107: { 108: return (original); 109: } 110: 111: public Type ReturnedType 112: { 113: get 114: { 115: return (typeof(Image)); 116: } 117: } 118: 119: public SqlType[] SqlTypes 120: { 121: get 122: { 123: return (new SqlType[] { new SqlType(DbType.Binary) }); 124: } 125: } 126: } In this case, we need to cache the original Byte[] data because it’s not easy to compare two Image instances, unless, of course, they are the same.

    Read the article

  • Castle ActiveRecord / NHibernate Linq Querys with ValueTypes

    - by Thomas Schreiner
    Given the following code for our Active Record Entites and ValueTypes Linq is not working for us. [ActiveRecord("Person")] public class PersonEntity : ActiveRecordLinqBase<PersonEntity> { string _name; [Property("Name", Length = 20, ColumnType = "string", Access = PropertyAccess.FieldCamelcaseUnderscore)] public Name Name { get { return NameValue.Create(_name);} set { _name = value.DataBaseValue; } } ... } public abstract class Name : IValueType { string DataBaseValue {get;set;} ... } public class Namevalue : Name { string _name; private NameValue(string name) { _name = name; } public static NameValue Create(string name) { return new NameValue(name); } ... } We tried to use linq in the following way so far with no success: var result = from PersonEntity p in PersonEntity.Queryable where p.Name == "Thomas" select p; return result.First(); // throws exception Cannot convert string into Name We tried and implemented a TypeConverter for Name, but the converter never got called. Is there a way to have linq working with this ValueTypes? Update: Using NHibernate.UserTypes.IUserType it sortof works. I Implemented the Interface as described here: http://stackoverflow.com/questions/1565056/how-to-implement-correctly-iusertype I still had to add a ConversionOperator from string to Name and had to call it Explicitly in the linq Statement, even though it was defined as implicit. var result = from PersonEntity p in PersonEntity.Queryable where p.Name == (Name)"Thomas" select p; return result.First(); //Now works

    Read the article

  • How do I map a one-to-one value type association in an joined-subclass?

    - by David Rubin
    I've got a class hierarchy mapped using table-per-subclass, and it's been working out great: class BasicReport { ... } class SpecificReport : BasicReport { ... } With mappings: <class name="BasicReport" table="reports"> <id name="Id" column="id">...</id> <!-- some common properties --> </class> <joined-subclass name="SpecificReport" table="specificReports" extends="BasicReport"> <key column="id"/> <!-- some special properties --> </joined-subclass> So far, so good. The problem I'm struggling with is how to add a property to one of my subclasses that's both a value type for which I have an IUserType implemented and also mapped via an association: class OtherReport : BasicReport { public SpecialValue V { get; set; } } class SpecialValueUserType : IUserType { ... } What I'd like to do is: <joined-subclass name="OtherReport" table="otherReports" extends="BasicReport"> <key column="id"/> <join table="rptValues" fetch="join"> <key column="rptId"/> <property name="V" column="value" type="SpecialValueUserType"/> </join> </joined-subclass> This accurately reflects the intent, and the pre-existing database schema I'm tied to: the SpecialValue instance is a property of the OtherReport, but is stored in a separate table ("rptValues"). Unfortunately, it seems as though I can't do this, because <join> elements can't be used in <joined-subclass> mappings. <one-to-one> would require creating a class mapping for SpecialValue, which doesn't make any sense given that SpecialValue is just a meaningful scalar. So what can I do? Do I have any options? Right now I'm playing a game with sets: class OtherReport : BasicReport { public SpecialValue V { get { return _values.Count() > 0 ? _values.First() : null; } set { _values.Clear(); _values.Add(value); } } private ICollection<SpecialValue> _values; } With mapping: <joined-subclass name="OtherReport" table="otherReports" extends="BasicReport"> <key column="id"/> <set name="_values" access="field" table="rptValues" cascade="all-delete-orphan"> <key column="rptId" /> <element column="value" type="SpecialValueUserType"/> </set> </joined-subclass> Thanks in advance for the help! I've been banging my head into my desk for several days now.

    Read the article

  • Using NHibernate with an EAV data model

    - by devonlazarus
    I'm trying to leverage NH to map to a data model that is a loose interpretation of the EAV/CR data model. I have most of it working but am struggling with mapping the Entity.Attributes collection. Here are the tables in question: -------------------- | Entities | -------------------- | EntityId PK |-| | EntityType | | -------------------- | ------------- | V -------------------- | EntityAttributes | ------------------ --------------------------- -------------------- | Attributes | | StringAttributes | | EntityId PK,FK | ------------------ --------------------------- | AttributeId FK | -> | AttributeId PK | -> | StringAttributeId PK,FK | | AttributeValue | | AttributeType | | AttributeName | -------------------- ------------------ --------------------------- The AttributeValue column is implemented as an sql_variant column and I've implemented an NHibernate.UserTypes.IUserType for it. I can create an EntityAttribute entity and persist it directly so that part of the hierarchy is working. I'm just not sure how to map the EntityAttributes collection to the Entity entity. Note the EntityAttributes table could (and does) contain multiple rows for a given EntityId/AttributeId combination: EntityId AttributeId AttributeValue -------- ----------- -------------- 1 1 Blue 1 1 Green StringAttributes row looks like this for this example: StringAttributeId AttributeName ----------------- -------------- 1 FavoriteColor How can I effectively map this data model to my Entity domain such that Entity.Attributes("FavoriteColors") returns a collection of favorite colors? Typed as System.String?

    Read the article

  • Phantom updates due to decimal precision on calculated properties

    - by Jamie Ide
    This article describes my problem. I have several properties that are calculated. These are typed as decimal(9,2) in SQL Server and decimal in my C# classes. An example of the problem is: Object is loaded with a property value of 14.9 A calculation is performed and the property value is changed to 14.90393 When the session is flushed, NHibernate issues an update because the property is dirty Since the database field is decimal (9,2) the stored value doesn't change Basically a phantom update is issued every time this object is loaded. I don't want to truncate the calculations in my business objects because that tightly couples them to the database and I don't want to lose the precision in other calculations. I tried setting scale and precision or CustomType("Decimal(9,2)") in the mapping file but this appears to only affect schema generation. My only reasonable option appears to be creating an IUserType implementation to handle this. Is there a better solution?

    Read the article

  • Nhibernate ValueType Collection as delimited string in DB

    - by JWendel
    Hi I have a legacy db that I am mapping with Nhibernate. And in several locations a list och strigs or domain objects are mapped as a delimited string in the database. Either 'string|string|string' in the value type cases and like 'domainID|domainID|domainID' in the references type cases. I know I can create a dummy property on the class and map to that fields but I would like to do it in a more clean way, like when mapping Enums as their string representation with the EnumStringType class. Is a IUserType the way to go here? Thanks in advance /Johan

    Read the article

  • Fluent NHibernate mapping List<Point> as value to single column

    - by Paja
    I have this class: public class MyEntity { public virtual int Id { get; set; } public virtual List<Point> Vectors { get; set; } } How can I map the Vectors in Fluent NHibernate to a single column (as value)? I was thinking of this: public class Vectors : ISerializable { public List<Point> Vectors { get; set; } /* Here goes ISerializable implementation */ } public class MyEntity { public virtual int Id { get; set; } public virtual Vectors Vectors { get; set; } } Is it possible to map the Vectors like this, hoping that Fluent NHibernate will initialize Vectors class as standard ISerializable? Or how else could I map List<Point> to a single column? I guess I will have to write the serialization/deserialization routines myself, which is not a problem, I just need to tell FNH to use those routines. I guess I should use IUserType or ICompositeUserType, but I have no idea how to implement them, and how to tell FNH to cooperate.

    Read the article

  • How do I create/use a Fluent NHibernate convention to automap UInt32 properties to an SQL Server 200

    - by dommer
    I'm trying to use a convention to map UInt32 properties to a SQL Server 2008 database. I don't seem to be able to create a solution based on existing web sources, due to updates in the way Fluent NHibernate works - i.e. examples are out of date. I'm trying to have NHibernate generate the schema (via ExposeConfiguration). I'm happy to have NHibernate map it to anything sensible (e.g. bigint). Here's my code as it currently stands (which, when I try to expose the schema, fails due to SQL Server not supporting UInt32). Apologies for the code being a little long, but I'm not 100% sure what is relevant to the problem, so I'm erring on the side of caution. Most of it is based on this post. The error reported is: System.ArgumentException : Dialect does not support DbType.UInt32 I think I'll need a relatively comprehensive example, as I don't seem to be able to pull the pieces together into a working solution, at present. FluentConfiguration configuration = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2008 .ConnectionString(connectionString)) .Mappings(mapping => mapping.AutoMappings.Add( AutoMap.AssemblyOf<Product>() .Conventions.Add<UInt32UserTypeConvention>())); configuration.ExposeConfiguration(x => new SchemaExport(x).Create(false, true)); namespace NHibernateTest { public class UInt32UserTypeConvention : UserTypeConvention<UInt32UserType> { // Empty. } } namespace NHibernateTest { public class UInt32UserType : IUserType { // Public properties. public bool IsMutable { get { return false; } } public Type ReturnedType { get { return typeof(UInt32); } } public SqlType[] SqlTypes { get { return new SqlType[] { SqlTypeFactory.Int32 }; } } // Public methods. public object Assemble(object cached, object owner) { return cached; } public object DeepCopy(object value) { return value; } public object Disassemble(object value) { return value; } public new bool Equals(object x, object y) { return (x != null && x.Equals(y)); } public int GetHashCode(object x) { return x.GetHashCode(); } public object NullSafeGet(IDataReader rs, string[] names, object owner) { int? i = (int?)NHibernateUtil.Int32.NullSafeGet(rs, names[0]); return (UInt32?)i; } public void NullSafeSet(IDbCommand cmd, object value, int index) { UInt32? u = (UInt32?)value; int? i = (Int32?)u; NHibernateUtil.Int32.NullSafeSet(cmd, i, index); } public object Replace(object original, object target, object owner) { return original; } } }

    Read the article

  • How do I create/use a Fluent NHibernate convention to map UInt32 properties to an SQL Server 2008 da

    - by dommer
    I'm trying to use a convention to map UInt32 properties to a SQL Server 2008 database. I don't seem to be able to create a solution based on existing web sources, due to updates in the way Fluent NHibernate works - i.e. examples are out of date. Here's my code as it currently stands (which, when I try to expose the schema, fails due to SQL Server not supporting UInt32). Apologies for the code being a little long, but I'm not 100% sure what is relevant to the problem, so I'm erring on the side of caution. I think I'll need a relatively comprehensive example, as I don't seem to be able to pull the pieces together into a working solution, at present. FluentConfiguration configuration = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2008 .ConnectionString(connectionString)) .Mappings(mapping => mapping.AutoMappings.Add( AutoMap.AssemblyOf<Product>() .Conventions.Add<UInt32UserTypeConvention>())); configuration.ExposeConfiguration(x => new SchemaExport(x).Create(false, true)); namespace NHibernateTest { public class UInt32UserTypeConvention : UserTypeConvention<UInt32UserType> { // Empty. } } namespace NHibernateTest { public class UInt32UserType : IUserType { // Public properties. public bool IsMutable { get { return false; } } public Type ReturnedType { get { return typeof(UInt32); } } public SqlType[] SqlTypes { get { return new SqlType[] { SqlTypeFactory.Int32 }; } } // Public methods. public object Assemble(object cached, object owner) { return cached; } public object DeepCopy(object value) { return value; } public object Disassemble(object value) { return value; } public new bool Equals(object x, object y) { return (x != null && x.Equals(y)); } public int GetHashCode(object x) { return x.GetHashCode(); } public object NullSafeGet(IDataReader rs, string[] names, object owner) { int? i = (int?)NHibernateUtil.Int32.NullSafeGet(rs, names[0]); return (UInt32?)i; } public void NullSafeSet(IDbCommand cmd, object value, int index) { UInt32? u = (UInt32?)value; int? i = (Int32?)u; NHibernateUtil.Int32.NullSafeSet(cmd, i, index); } public object Replace(object original, object target, object owner) { return original; } } }

    Read the article

1