How to map object type field in Nhibernate Auto Mapping - nhibernate

When trying to map, I got this error:
Association references unmapped class: System.Object
My class:
public partial class MessageIdentifier
{
public virtual int ID { get; set; }
public virtual object Item { get; set; }
}
And the convention:
public class MyUsertypeConvention : IPropertyConvention
{
public void Apply(IPropertyInstance instance)
{
if (instance.Type.Name == "Object")
instance.CustomType<string>();
}
}
Kindly suggest how to map?

As a simple (quick, naive) solution - I would suggest to create and map real string property. And then let your setter and getter (or some AOP or listener) to do the "to/from string conversion":
public partial class MessageIdentifier
{
public virtual int ID { get; set; }
public virtual object Item
{
get { return ... my conversion from string; }
set { ItemString = ...my conversion to string; }
}
public virtual string ItemString { get; set; }
}
A smart and preferred (but a bit more challenging) is to create CustomType - which will hide that conversion and support REUSE. Check e.g. here
NHibernate Pitfalls: Custom Types and Detecting Changes
Creating and Testing a Custom NHibernate User Type

Not a satisfactory answer. It doesn't work with class that is generated from xsd by using XML. You can try the following:
public partial class MessageIdentifier
{
public virtual int ID { get; set; }
private object itemField;
public object Item
{
get { return this.itemField; }
set { this.itemField = value; }
}
}

Related

Can not implement discriminated union and serialize it

Hello i am trying to create a hierarchy of classes using a discriminated unionand it seems i can't serialize them.I keep getting this error :
Newtonsoft.Json.JsonSerializationException: 'Self referencing loop detected for property 'AsRun' with type 'MsgPattern.Message+Run'. Path ''.'
Base class
[Serializable]
public abstract partial class Message {
public enum Type {
WALK = 0,
RUN = 1
}
protected abstract Type Discriminator { get; }
public Type Kind => this.Discriminator;
internal static Message Create(string data) {
var message = JsonConvert.DeserializeObject<Message>(data);
switch (message.Kind) {
case Type.RUN:message= message.AsRun;break;
case Type.WALK:message= message.AsWalk;break;
}
return message;
}
[JsonIgnore]
public bool IsWalk => this.Kind==Type.Walk;
[JsonIgnore]
public bool IsRun => this.Kind==Type.Run;
[JsonIgnore]
public Message.Walk AsWalk => this as Message.Walk;
[JsonIgnore]
public Message.Run AsRun => this as Message.Run;
}
Dervived
partial class Message {
public class Run : Message {
protected override Type Discriminator => Type.RUN;
public string Location { get; set; }
public int Speed { get; set; }
}
}
partial class Message {
public class Walk : Message {
protected override Type Discriminator => Type.WALK;
public int Gait { get; set; }
public bool IsJogging { get; set; }
}
}
Usage
class Program {
static void Main(string[] args) {
Message.Run run = new Message.Run { Location = "asa", Speed = 33 };
string data = JsonConvert.SerializeObject(run);
Message msg=Message.Create(data);
}
}
I will get these type of messages via json and i want to be able to do actions based on their type. I do not understand why i can't serialize them .
P.S I know it's a self-referencing loop but I need those As[something] and Is[Something] fields.

exception:"type was not mapped" in entityframework codefirst with layers

i'm trying to apply LAYERS Concept on demo project developed using mvc and entity framework both
Data Annotations : for validations in Data Access Layer and
Fluent API : for mapping and tables relations
Problem : DbContext didn't Create DB and there is a Runtime Exception :
The type 'Domain.DataLayer.Member' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject.
Code : my solutions consists of :
1- class library (Domain.Classes project): where i wrote all of my classes
public class Member
{
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string FullName { get; set; }
}
2- DAL (Domain.DataLayer project): also another class library and i referenced domain.classes
namespace Domain.DataLayer.Repositories
{
[MetadataType(typeof(MemberMetadata))]
public partial class Member : Classes.Member , IValidatableObject
{
public Member()
{
Tasks = new HashSet<Task>();
History = new HashSet<Commint>();
}
public string ConfirmPassword { get; set; }
public HashSet<Task> Tasks { get; set; }
public HashSet<Commint> History { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var result = new List<ValidationResult>();
if (!string.Equals(Password,ConfirmPassword))
{
result.Add(new ValidationResult("mismatch pwsd", new[] {"ConfirmPassword" }));
}
return result;
}
}
}
and i used repository pattern :
public class MemberRepository : IRepository<Member>
{
public Task<IQueryable<Member>> GetAllEntities()
{
return Task<IQueryable<Member>>.Factory.StartNew(() => new Context().Members.AsQueryable());
}
}
3-BLL : for sake of simplicity : there is no Business Logic Layer
4- PL (Domain.Application MVC Project) : Member Controller :
public async Task<ActionResult> Index()
{
var members = await _repository.GetAllEntities();
return View(members);
}
Note : i depended on DbContext to create DB with name like : Domain.DataLayer.Context but it didn't craete DB so i created the DB and passed the connectionString through Context constructor like this :
namespace Domain.DataLayer
{
public class Context : DbContext
{
public Context(): base("InterviewDemo") // i tried also base("name=InterviewDemo")
{
}
public DbSet<Member> Members { get; set; }
public DbSet<Task> Tasks { get; set; }
public DbSet<Commint> TaskHistory { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new MemberConfig());
modelBuilder.Configurations.Add(new TaskConfig());
modelBuilder.Configurations.Add(new CommintConfig());
base.OnModelCreating(modelBuilder);
}
}
}

NHibernate - IUserType For Changing Type?

My application has the following classes:
public class Widget {
public virtual int Id { get; set; }
public virtual WidgetType Type { get; set; }
public virtual string Parameters { get; set; }
}
public class WidgetType {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string ParametersAssembly { get; set; }
public virtual string ParametersClass { get; set; }
}
Now if i'd like to update the Parameters for a particular widget i would say something like:
// Get the widget
var widget = GetWidget(1);
// Create an instance of the type parameters class
var parameters = Activator.CreateInstance(Assembly.LoadFrom(Server.MapPath("~/bin/"
+ widget.Type.ParametersAssembly + ".dll")).GetType(widget.Type.ParametersClass));
... Code here to update the parameters
widget.Parameters = new XmlSerializer(parameters.GetType()).Serialize(parameters);
I have to do the reverse when i wish to get the parameters. You can imagine this becomes quite tedious. I was wondering if it was possibly to automatically do this?
I've been looking at the IUserType interface. I found an article which is kind of similar. However my problem is a little more complicated as my type changes based on the type of the widget.
I'd appreciate it if someone could let me know if this is possible and possibly how it could be achieved. Thanks
an easy way
public class Widget
{
public virtual int Id { get; set; }
public virtual WidgetType Type { get; set; }
private string _serializedParameters;
private virtual string SerializedParameters {
get
{
return new XmlSerializer(Parameters.GetType()).Serialize(Parameters);
}
set
{
_serializedParameters = value;
// code to deserialize the Parameters and set to Parameters
var ptype = Assembly.LoadFrom(Server.MapPath("~/bin/" + widget.Type.ParametersAssembly + ".dll")).GetType(widget.Type.ParametersClass);
Parameters = Activator.CreateInstance(ptype);
}
}
private object _parameters;
public virtual object Parameters
{
get
{
if (_parameters == null)
_parameters = Activator.CreateInstance(Assembly.LoadFrom(Server.MapPath("~/bin/" + widget.Type.ParametersAssembly + ".dll")).GetType(widget.Type.ParametersClass));
return _parameters;
}
set { _parameters = value; }
}
}
it can't be in the Parameters property because then you have to get -> alter -> set instead of get -> alter. But you are right that building the parameters object should go in the getter of Parameters because only there we can be sure to have the WidgetType loaded
it is essentially the same as a UserType except that we know that WidgetType is there

Dynamic Proxy : wrapping constructors

I'm taking a stab at creating a Active Record implementation (I know about Castle's initiative, and it's very good) for another type of data provider (ESRIs geodatabases, using ESRIs .NET libraries) and I'm reaching something interesting.
I have a question nevertheless. I have my ActiveRecord classes which is like this:
public interface IActiveRecord<T> : IActiveRecord where T : class
{
T Create();
void Update(T record);
void Delete(T record);
}
public interface IActiveRecord
{
int ObjectId { get; set; }
bool Managed { get; }
bool IsValid { get; }
IObject EsriObject { get; set; }
IGeometry Geometry { get; set; }
void Save();
void Delete();
}
I have static Create methods, which go to DynamicProxy and generate me a proxy. But how I can enforce that the instance generated for a inheriting class is proxied too?
public class ActiveRecord<T> : IActiveRecord where T : IActiveRecord,new()
{
// protected constructors
public static T Create(IObject obj)
{
var record = Create();
record.EsriObject = obj;
return (T)record;
}
}
// inherited class
[Workspace(#"C:\teste.gdb")]
[Table("TB_PARCEL",Geometry=esriGeometryType.esriGeometryPolygon)]
public class Parcel : ActiveRecord<Parcel>,IParcel
{
[Field(4, "NM_PARCEL_ID", esriFieldType.esriFieldTypeString)]
public virtual string ParcelId { get; set; }
[Field(5, "NR_PARCEL_NO", esriFieldType.esriFieldTypeInteger)]
public virtual int StreetNumber { get; set; }
public virtual IOwner ParcelOwner { get; set; }
}
Take a look at the tests. The first three tests get intercepted as usual, but not the fourth test. I need A) prevent the user from instancing it's own classes (bad approach for the API in my opinion) or find a way to return from the inherited classes constructors the proxies.
[TestMethod]
public void ActiveRecordConstructor()
{
Parcel p1 = Parcel.Create();
Assert.IsFalse(p1.Managed);
Assert.AreEqual(null, p1.ParcelId);
Parcel p2 = Parcel.Create(2);
Assert.IsFalse(p2.Managed);
IObject fake = _repository.StrictMock<IObject>();
using (_repository.Record())
{
fake.Stub(x => x.get_Value(4)).Return("teste");
}
using (_repository.Playback())
{
Parcel p3 = Parcel.Create(fake);
Assert.IsTrue(p3.Managed);
Assert.AreEqual("teste", p3.ParcelId);
}
// this wont be intercepted
Parcel p4 = new Parcel();
Assert.IsFalse(p4.Managed);
Assert.IsNull(p4.ParcelId);
}
In short I need that whenever a user creates a new Class(), it returns a proxied object. Is that possible while allowing inheritance?
Thanks!
DynamicProxy cannot intercept calls to constructors. It has to control the creation of the object.

Fluent NHibernate and class with indexer mapping

How can I map the class AttributeSet with Fluent NHibernate using a fluent mapping
public class AttributeSet : DictionaryBase
{
private readonly Dictionary<string, object> _cache;
public AttributeSet()
{
_cache = new Dictionary<string, object>();
}
public object this[string index]
{
get
{
return _cache[index];
}
set
{
_cache[index] = value;
}
}
}
public class Entity
{
protected Entity()
{
Attributes = new AttributeSet();
}
public virtual int Id { get; set; }
public virtual string Label { get; set; }
public virtual string Description { get; set; }
public virtual DateTime CreatedDate { get; set; }
public virtual AttributeSet Attributes { get; set; }
}
I don't think there's a way to map your indexer directly, but you can expose the underlying dictionary type and map that instead.
If you don't want to expose the dictionary as public you can map it as a private property instead as explained here. For mapping a dictionary, see here.
An example might be
HasMany<object>(Reveal.Member<AttributeSet>("Cache"))
.KeyColumn("AttributeSetId")
.AsMap<string>(idx => idx.Column("Index"), elem => elem.Column("Value"))
.Access.CamelCaseField(Prefix.Underscore)
Mapping the object type in the dictionary might be interesting, I don't know if NHibernate will be able to translate it directly to an underlying database type.