My application has the following types defined
public interface IUser {
int Id { get; set; }
int UserName { get; set; }
}
public class User : IUser {
public virtual int Id { get; set; }
public virtual string UserName { get; set; }
}
The User class is fluently mapped like:
public class UserMap : ClassMap<User> {
public UserMap() {
Table("Users");
Id(x => x.Id);
Map(x => x.UserName);
}
}
I’d like to create another implementation of IUser but i have a couple restrictions:
- The new fields must be added to the same table as the Users table
- The code to extend the type exists in a seperate project
For example here is my new class:
public class CustomUser : IUser {
public virtual int Id { get; set; }
public virtual string UserName { get; set; }
public virtual string Name { get; set; }
}
Which is mapped like:
public class CustomUserMap : ClassMap<CustomUser> {
public CustomUserMap() {
Table("Users");
Id(x => x.Id);
Map(x => x.UserName);
Map(x => x.Name);
}
}
The first problem i had with this was that it did not like the same interface to be mapped twice. I overcame this by adding some code in the Application_Start event to only add the UserMap class if no CustomUserMap class existed.
However i soon ran into my next problem, if i add a reference to the IUser interface in another type, it throws the error:
An association from the table Blogs refers to an unmapped class: IUser
I’m probably going about things completely wrong and i’d appreciate it if someone could show me what i’m doing wrong. Thanks
If you want them to map to the same table, why don’t you inherit User? That will also implement the IUser interface.
In order to prevent duplicate selects (when fetching User, it might fetch the CustomerUser in a second roundtrip), you need to specify polymorphism explicit on the User class. In hbm files this would be polymorphism=”explicit”, don’t know about fluent nhibernate.