I am attempting to use the Fluent-NHibernate automapping functionality (in the latest version of the software) and am running into problems using Guids as the Primary Key fields. If I use integer fields for the primary keys, the tables are generated successfully and all Nhibernate functionality seems to work fine. FYI, I am using NHibernate to generate my database tables.
Here are a couple of classes with integer IDs.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
namespace Sample.Data.Entities
{
public class Employee
{
public virtual int Id { get; private set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual Store Store { get; set; }
}
public class Product
{
public virtual int Id { get; private set; }
public virtual string Name { get; set; }
public virtual double Price { get; set; }
public virtual IList<Store> StoresStockedIn { get; private set; }
public Product()
{
StoresStockedIn = new List<Store>();
}
}
public class Store
{
public virtual int Id { get; private set; }
public virtual string Name { get; set; }
public virtual IList<Product> Products { get; set; }
public virtual IList<Employee> Staff { get; set; }
public Store()
{
Products = new List<Product>();
Staff = new List<Employee>();
}
public virtual void AddProduct(Product product)
{
product.StoresStockedIn.Add(this);
Products.Add(product);
}
public virtual void AddEmployee(Employee employee)
{
employee.Store = this;
Staff.Add(employee);
}
}
}
Here are the same classes with GUIDs.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
namespace Sample.Data.Entities
{
public class Employee
{
public virtual Guid Id { get; private set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual Store Store { get; set; }
}
public class Product
{
public virtual Guid Id { get; private set; }
public virtual string Name { get; set; }
public virtual double Price { get; set; }
public virtual IList<Store> StoresStockedIn { get; private set; }
public Product()
{
StoresStockedIn = new List<Store>();
}
}
public class Store
{
public virtual Guid Id { get; private set; }
public virtual string Name { get; set; }
public virtual IList<Product> Products { get; set; }
public virtual IList<Employee> Staff { get; set; }
public Store()
{
Products = new List<Product>();
Staff = new List<Employee>();
}
public virtual void AddProduct(Product product)
{
product.StoresStockedIn.Add(this);
Products.Add(product);
}
public virtual void AddEmployee(Employee employee)
{
employee.Store = this;
Staff.Add(employee);
}
}
}
Here is my configuration.
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(c => c.FromConnectionStringWithKey("AAAConnectionString"))
.UseReflectionOptimizer()
.AdoNetBatchSize(25)
.DefaultSchema("dbo")
.Cache(c => c
.UseQueryCache()
.ProviderClass<HashtableCacheProvider>())
.ShowSql())
.Mappings(m=>m.AutoMappings
.Add(AutoMap.AssemblyOf<Sample.Data.Entities.Product>()
.Where(type => type.Namespace == "Sample.Data.Entities.Product")
.Conventions.AddFromAssemblyOf<Sample.Data.Fluent.Conventions.PrimaryKeyNameConvention>()
))
.ExposeConfiguration(BuildSchema)
.BuildSessionFactory();
To work around the issue, I attempted to generate conventions (see below) for 1) naming the Id field (although I thought it should have been unnecessary) and for 2) generating the Id (which I thought would have been automatic). I am unsure what is happening or why this is not working.
public class PrimaryKeyNameConvention : IIdConvention
{
public bool Accept(IIdentityInstance id)
{
return true;
}
public void Apply(IIdentityInstance id)
{
id.Column("Id");
}
}
public class PrimaryKeyGeneratorConvention : IIdConvention
{
public bool Accept(IIdentityInstance id)
{
return true;
}
public void Apply(IIdentityInstance id)
{
id.GeneratedBy.GuidComb();
}
}
Also, if I turn automapping off and use Fluently configured map the tables are generated successfully.
This is driving me nuts, and I am sure it is probably a quick fix. Any ideas?
Thank you!
Anthony
Apparently, there was an issue in the Fluent Nhibernate version 1.0RC and version 1.0. However, if you download the latest version from the SVN trunk, every thing works perfectly. It appears that the problem was simply a bug in the code which has now been corrected.
Also, I should note that James Gregory, Paul Batum, and perhaps others, are actively working on Fluent NHibernate. The product is evolving pretty dramatically and there have been significant changes to the code over the last couple of months.
Related
I think entity framework has problem while generating database in my project. That's strange that it only happens in one case. This is one to many relationship between "User" and "Playlist". One User has many Playlists.
Here is my code, I used some abstract classes in my project.
Core code
Playlist class
public virtual User User { get; set; }
User class
public virtual ICollection<Playlist> Playlists { get; set; }
The full code:
Generic class:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace xxx.Areas.admin.Models
{
public abstract class Generic
{
[Display(Name = "Ngày tạo")]
public DateTime? Created { get; set; }
[Display(Name = "Lần sửa cuối")]
public DateTime? Modified { get; set; }
[Display(Name = "Trạng thái")]
public bool? IsActive { get; set; }
}
}
Post class:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace xxx.Areas.admin.Models
{
public abstract class Post : Generic
{
public string Title { get; set; }
public string Slug { get; set; }
public string Content { get; set; }
public string Image { get; set; }
public int Views { get; set; }
public bool? AllowComment { get; set; }
public User ModifiedBy { get; set; }
public virtual ICollection<Media> Medias { get; set; }
}
}
AlbumBase class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using xxx.Areas.admin.Models.SongBase;
namespace xxx.Areas.admin.Models.AlbumBase
{
public abstract class AlbumBase : Post
{
public bool IsPublic { get; set; }
public bool IsFeatured { get; set; }
public int OldID { get; set; }
public string OldSlug { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
}
Playlist class:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using xxx.Areas.admin.Models.SongBase;
namespace xxx.Areas.admin.Models.AlbumBase
{
public class Playlist : AlbumBase
{
[Key]
public int PlaylistID { get; set; }
public virtual ICollection<Song> Songs { get; set; }
public virtual ICollection<Folk> Folks { get; set; }
public virtual ICollection<Instrumental> Instrumentals { get; set; }
public virtual User User { get; set; }
public Playlist()
{ }
public Playlist(string name)
{
Title = name;
Slug = Functions.URLFriendly(Title);
Views = 0;
OldID = 0;
AllowComment = true;
IsActive = true;
IsPublic = false;
IsFeatured = false;
Created = DateTime.Now;
}
}
}
and User class:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using baicadicungnamthang.Areas.admin.Models.AlbumBase;
using baicadicungnamthang.Areas.admin.Models.Social;
using baicadicungnamthang.DAL;
using ICB;
namespace xxx.Areas.admin.Models
{
public class User : Generic
{
[Key]
public int UserID { get; set; }
[Required(ErrorMessage = "Bạn phải nhập tên tài khoản"), StringLength(50)]
public string UserName { get; set; }
public string Password { get; set; }
public string HashPassword { get; set; }
[Required(ErrorMessage = "Bạn phải nhập địa chỉ email"), EmailAddress(ErrorMessage = "Địa chỉ email không hợp lệ")]
public string Email { get; set; }
[StringLength(50)]
public string NickName { get; set; }
public string FullName { get; set; }
public string Slug { get; set; }
public string Title { get; set; }
public string Phone { get; set; }
public string Avatar { get; set; }
public DateTime? DOB { get; set; }
[StringLength(1)]
public string Gender { get; set; }
public string Address { get; set; }
public int TotalLikes { get; set; }
public int TotalComments { get; set; }
public int Views { get; set; }
public string ActivationKey { get; set; }
public string RecoverKey { get; set; }
public DateTime? LastLogin { get; set; }
public int OldID { get; set; }
public virtual Role Role { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
public virtual ICollection<Comment> RateComments { get; set; }
public virtual ICollection<Playlist> Playlists { get; set; }
public virtual ICollection<User> Friends { get; set; }
public virtual ICollection<Message> MessagesSent { get; set; }
public virtual ICollection<Message> MessagesReceived { get; set; }
public User()
{
Created = DateTime.Now;
IsActive = false;
TotalLikes = 0;
Views = 0;
OldID = 0;
}
public string getAvatar(int w, int h)
{
return Functions.getAvatarThumb(UserName, w, h);
}
public int getAge()
{
if (DOB == null)
{
return 0;
}
else
{
DateTime now = DateTime.Now;
int age = now.Year - DOB.Value.Year;
return age;
}
}
public string getGender()
{
if (Gender == "M")
{
return "Nam";
}
else if (Gender == "F")
{
return "Nữ";
}
else return "";
}
}
}
And this is Playlist table generating from code first:
As you see, entity framework has generated two columns: User_UserID and User_UserID1 from primary key UserID of User table.
I say that because when I uncomment the line
//public virtual User User { get; set; }
and rebuild the project, the two column User_UserID and User_UserID1 has disappeared too.
The problem only happens with User and Playlist relationship. With other one-to-many scenarios (User-Comments), system work well.
Can anyone give me a suggestion?
The problem is that you have multiple relationships between the same entities.
Playlist has 2 references to User (one in the Playlist class and one in its base class Post).
This confuses Entity Framework, because it doesn't know how to map the relationships, which is why it creates too many foreign keys in the database.
To fix this you can use the InverseProperty attribute to tell it how to map the navigation properties:
public class Playlist : AlbumBase
{
[Key]
public int PlaylistID { get; set; }
[InverseProperty("Playlists")]
public virtual User User { get; set; }
......
I have an EntityBase class for FluentNHibernate:
public abstract class EntityBase<T>
{
public EntityBase()
{
}
public static T GetById(int id)
{
return (T)Hibernate.Session.Get<T>(id);
}
public virtual void Save()
{
using (var transaction = Hibernate.Session.BeginTransaction())
{
Hibernate.Session.SaveOrUpdate(this);
transaction.Commit();
}
}
public static IList<T> List()
{
return Hibernate.Session.CreateCriteria(typeof(T)).List<T>();
}
public static IList<T> ListTop(int i)
{
return Hibernate.Session.CreateCriteria(typeof(T)).SetMaxResults(i).List<T>();
}
public virtual void Delete()
{
using (var transaction = Hibernate.Session.BeginTransaction())
{
Hibernate.Session.Delete(this);
transaction.Commit();
}
}
}
I have a base member class also a table in database:
abstract public class BaseMember:EntityBase<BaseMember>
{
public virtual int Id { get; set; }
public virtual string Email { get; set; }
public virtual string Password { get; set; }
public virtual string RecordDate { get; protected set; }
public BaseMember()
{
}
}
I have another Member class that is deriving from BaseMember class:
public class IndividualMember : BaseMember
{
public virtual int Id { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual string PhoneNumber { get; set; }
public virtual string MobilePhoneNumber { get; set; }
public virtual DateTime BirthDate { get; set; }
public virtual bool Gender { get; set; }
public virtual string ProfileImage { get; set; }
public virtual string AddressDefinition { get; set; }
public virtual string ZipCode { get; set; }
public virtual DateTime RecordDate { get; set; }
public IndividualMember()
{
}
}
How can I map those classes with BaseMember and IndividualMember tables in db?
There are different types of Inheritance mapping strategies in Fluent NHibernate.
You can use SubclassMap mapping for derived class.
Strategies : Table-per-class-hierarchy, Table-per-subclass and Table Per Concrete Class.
For table-per-class-hierarchy strategy, you just need to specify the discriminator column.
For more reference :
http://www.codeproject.com/Articles/232034/Inheritance-mapping-strategies-in-Fluent-Nhibernat
https://github.com/jagregory/fluent-nhibernate/wiki/Fluent-mapping#wiki-subclasses
I have just started working on a project using Fluent NHibernate.
What is the correct way to map the following classes using Fluent NHibernate?
public class DurationUnit
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
public class Duration
{
public virtual int Value { get; set; }
public virtual DurationUnit Unit { get; set; }
public virtual int DurationInMinutes { get{ throw new NotImplementedException(); } }
}
public class Event
{
public virtual int Id { get; set; }
public virtual String Name { get; set; }
public virtual Duration MaxDuration { get; set; }
public virtual Duration MinDuration { get; set; }
}
My inital approach was to declare a ClassMap for DurationUnit and Event, with Duration as a component of Event. When trying this I received an exception:
NHibernate.MappingException: Could not determine type for:
Entities.DurationUnit
if your mapping looks like this
public EventMap()
{
Component(x => x.MaxDuration, c =>
{
c.Map(x => x.Value, "MaxDurationValue");
c.Reference(x => x.Unit, "MaxDurationUnitId");
});
}
then make sure class DurationUnitMap is public and is added to the configuration
I'm using ASP.NET MVC with NHibernate and Fluent.NHibernate Maps.
I would like to know how to map the classes on Fluent and to create the database tables on my MySQL:
public class AgenteDeViagem {
public virtual int Id { get; set; }
public virtual string Email { get; set; }
public virtual AgentePessoa AgentePessoa { get; set; }
}
public interface AgentePessoa {
}
public class AgenteDeViagemPJ:AgentePessoa {
public virtual int Id { get; set; }
public virtual AgenteDeViagem AgenteDeViagem { get; set; }
public virtual string Razao { get; set; }
}
public class AgenteDeViagemPF:AgentePessoa {
public virtual int Id { get; set; }
public virtual AgenteDeViagem AgenteDeViagem { get; set; }
public virtual string Nome { get; set; }
}
Thank you very much!
Looks to me like you're halfway there. You're already using virtual and relations are set, so using the Automapping strategy, you only need to build the session factory:
private static ISessionFactory InitializeNHibernate()
{
var cfg = Fluently.Configure()
.Database(MySQLConfiguration.Standard.ConnectionString(c =>
c.Database("agente").Server("localhost")
.Username("user").Password("password")))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<AgenteDeViagem>())
.ExposeConfiguration(configuration =>
{
// Comment to disable schema generation
BuildDatabaseSchema(configuration);
});
return cfg.BuildSessionFactory;
}
private static void BuildDatabaseSchema(Configuration configuration)
{
var schemaExport = new SchemaExport(configuration);
schemaExport.SetOutputFile("mysql_script.sql");
schemaExport.Create(false, true);
}
I am getting the following exception when calling any of my Mapper.Map methods.
Inheritance security rules violated while overriding member: 'Castle.Core.Logging.LevelFilteredLogger.InitializeLifetimeService()'.
Security accessibility of the overriding method must match the
security accessibility of the method being overriden.
I am using the latest build of AutoMapper downloaded from codeplex inside my S#arp 1.6 application running on .Net 4.0 (which is using version 1.2.0.6623 of Castle.Core).
I beleive it has something to do with the new .Net 4.0 security settings which I don't quite understand.
Is there a way to fix it?
Paul
I tried something from a little googling which fixed my problem, i'm not sure if this is the ideal or recommended approach but it worked.
I added this to the Automapper projects 'AssemblyInfo.cs' file:
[assembly: System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]
I recompiled and used the new DLL and everything worked fine.
Please leave comments if this isn't reccomended or if there is a better approach.
For now though i will leave my own answer as the correct one.
Thanks for the help though!
UPDATE:
My mappings are pretty simple, sorry about all the code but thought it may help you:
Initialisation Code:
Mapper.Reset();
Mapper.Initialize(x =>
{
x.AddProfile<LeadsProfile>();
//x.AddProfile<AttendeeProfile>();
});
Mapper.AssertConfigurationIsValid();
LeadsProfile.cs
public class LeadsProfile : AutoMapper.Profile
{
public override string ProfileName
{
get { return "LeadsProfile"; }
}
protected override void Configure()
{
Mapper.CreateMap<Lead, LeadDto>();
Mapper.CreateMap<Lead, LeadDetailDto>();
Lead lead = null;
Mapper.CreateMap<int, LeadDetailDto>()
.BeforeMap((s, d) => lead = ServiceLocator.Current.GetInstance<ILeadRepository>().FindOne(s))
.ForMember(d => d.Id, x => x.MapFrom(s => lead.Id))
.ForMember(d => d.Fullname, x => x.MapFrom(s => lead.Fullname))
.ForMember(d => d.TelNumber, x => x.MapFrom(s => lead.TelNumber))
.ForMember(d => d.BookedAppointmentDate, x => x.MapFrom(s => lead.BookedAppointmentDate));
}
}
Source Class
public class Lead : Entity
{
public Lead()
{
Status = Common.LeadStatus.Raw;
CreatedDate = DateTime.Now;
}
public Lead(Branch branch, Promoter promoter, LeadSource source, string fullname, string telNumber, Address address, DateTime apptDate) : this()
{
this.Branch = branch;
this.Promoter = promoter;
this.Source = source;
this.Fullname = fullname;
this.TelNumber = telNumber;
this.Address = address;
this.BookedAppointmentDate = apptDate;
}
public virtual Branch Branch { get; set; }
public virtual Promoter Promoter { get; set; }
public virtual LeadSource Source { get; set; }
public virtual Common.LeadStatus Status { get; set; }
public virtual bool ExistingCustomer { get; set; }
public virtual bool IsDoso { get; set; }
public virtual string TitlePrefix { get; set; }
public virtual string Fullname { get; set; }
public virtual string TelNumber { get; set; }
public virtual string MobileNumber { get; set; }
public virtual DateTime BookedAppointmentDate { get; set; }
public virtual Address Address { get; set; }
public virtual Store Store { get; set; }
public virtual IList<LeadProduct> Products { get; set; }
public virtual IList<Appointment> Appointments { get; set; }
public virtual IList<Sale> Sales { get; set; }
public virtual DateTime CreatedDate { get; set; }
}
Destination Dto's
public class LeadDto
{
public int Id { get; set; }
public string Fullname { get; set; }
public string TelNumber { get; set; }
public DateTime BookedAppointmentDate { get; set; }
}
public class LeadDetailDto
{
public int Id { get; set; }
public string Fullname { get; set; }
public string TelNumber { get; set; }
public DateTime BookedAppointmentDate { get; set; }
}
I'd try upgrading Castle.Core to 2.5, which has been built and tested specifically against .net 4.0. (I should note that Castle.Core 2.5 is also available for .net 3.5 and SL 3/4)
Related questions:
Log4Net and .NET 4.0 RC
Weird override problem with Fluent NHibernate and .NET 4