ManyToManyMapping With Fluent Nhibernate?
Feb 16, 2011I have a table USERS and GROUPS table.
I want to add another table UserGroups.
How can I map these tables.
I have a table USERS and GROUPS table.
I want to add another table UserGroups.
How can I map these tables.
, I want to use fluent hibernate with asp.net but couldn't find any website or tutorial for that , they're all to configure it with asp.net mvc , anyone knows any?
View 3 RepliesI have a session criteria statement (Fluent NHibernate) that does not seem to filter the child collection even though I have Expressions/Restrictions defined.
ICriteria criteria = session.CreateCriteria(typeof(MyClass));
criteria.CreateAlias("MyCollection", "MC");
criteria.Add(Restriction.Eq("MC.Property", value));
IList<MyClass> list = criteria.List<MyClass>();
This returns all the objects of type MyClass that have MyCollection.Property = value, however MyCollection is not filtered to MyCollection.Property = value
It seems like only the Root objects get filtered.
I am getting this error even though all my mappings are pretty simple and correct. I get this error only on select classes.
View 1 RepliesWe are developing a multi-language web application with ASP.NET MVC 2 and Fluent NHibernate.Our platform will be multi-language. But just static text will be multi-language. Groups pages depends on community content whatever they use. Like Facebook.We decide to keep all language string in database. And load language when application starts.
View 1 RepliesI have the following models & mappings (code snippets further below).
One Competition has to have multiple CompetitionAnswers associated with it (multiple choice) from the outset.
At present, using the Fluent NHibernate mappings shown below, when I create a brand new Competition object, populate the properties, then create 3 brand new CompetitionAnswer objects and add them to the CompetitionAnswers property (property on Competition), I would expect to call Save on the session which would INSERT the 1 Competition row and 3 CompetitionAnswer rows to the DB.
However, as soon as I try to call Save on the session, it complains that CompetitionId is null and it can't insert a null into the CompetitionAnswers table for that field - which is right, it shouldn't, however, I assumed that the NHibernate would first create the Competition, then use the newly generated IDENTITY value (CompetitionId) in the CompetitionAnswers table?
[code]....
I've upgraded an ASP.Net Web application to the latest build of Fluent NHibernate (1.0.0.636) and the newest version of NHibernate (v2.1.2.4000). I've checked a couple of times that the application is running in Full trust. But I keep getting the following error:
Security Exception
Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.
Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SecurityException: Request for the permission of type 'System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
System.Security.CodeAccessPermission.Demand() +54
System.Reflection.Emit.DynamicMethod.PerformSecurityCheck(Type owner, StackCrawlMark& stackMark, Boolean skipVisibility) +269
System.Reflection.Emit.DynamicMethod..ctor(String name, Type returnType, Type[] parameterTypes, Type owner, Boolean skipVisibility) +81
NHibernate.Bytecode.Lightweight.ReflectionOptimizer.CreateDynamicMethod(Type returnType, Type[] argumentTypes) +165
NHibernate.Bytecode.Lightweight.ReflectionOptimizer.GenerateGetPropertyValuesMethod(IGetter[] getters) +383
NHibernate.Bytecode.Lightweight.ReflectionOptimizer..ctor(Type mappedType, IGetter[] getters, ISetter[] setters) +108
NHibernate.Bytecode.Lightweight.BytecodeProviderImpl.GetReflectionOptimizer(Type mappedClass, IGetter[] getters, ISetter[] setters) +52
NHibernate.Tuple.Component.PocoComponentTuplizer..ctor(Component component) +231
NHibernate.Tuple.Component.ComponentEntityModeToTuplizerMapping..ctor(Component component) +420
NHibernate.Tuple.Component.ComponentMetamodel..ctor(Component component) +402
NHibernate.Mapping.Component.BuildType() +38
NHibernate.Mapping.Component.get_Type() +32
NHibernate.Mapping.SimpleValue.IsValid(IMapping mapping) +39
NHibernate.Mapping.RootClass.Validate(IMapping mapping) +61
NHibernate.Cfg.Configuration.ValidateEntities() +220
NHibernate.Cfg.Configuration.Validate() +16
NHibernate.Cfg.Configuration.BuildSessionFactory() +39
FluentNHibernate.Cfg.FluentConfiguration.BuildSessionFactory() in d:BuildsFluentNHsrcFluentNHibernateCfgFluentConfiguration.cs:93
Anyone had a similar error? I've seach the web / stackoverflow / NHibernate forums but only found people who had a problem when running in medium trust mode, not full trust. I've been developing for several months on this application on this machine with previous versions of Fluent NHibernate and NHibernate.
The machine I'm running this on is 64-bit, you never know that this is relevant.
with fluent nhibernate, is there a way to dynamically switch the table of a mapping at runtime?
public class XYClassMap : ClassMap<XY>
{
public XYClassMap( )
{
Table("XYTable");
Id(d => d.Id).GeneratedBy.Identity();
Map(d => d.Value);
[code]...
I am using the above combo in a new web app Im doing just to try to learn to build new stuff to expand my knowledge. Im hoping to go live if I do a good job.. Im kind of new at MVC and the other products so I was trying to find a link to a good tutorial that set all of these up together.
View 1 RepliesI'm trying to update the data in the parent table that is referenced in the child table from the child's view in Asp.net.
I mapped the tables using Fluent Nhibernate.
In the child table, the mapping looks like this:
[code]....
this is my very very first project with fluent hibernate.i've had small experience in hibernate and nhibernate:
This context is completely new to me since this is a web app project.
So i have my webapp project with most of the fluent nhibernate found on the net.
so i have This entities:
[code]....
I'm working on a RoleProvider in .NET, using Fluent NHibernate to map tables in an Oracle 9.2 database.
The problem is that the many-to-many table connecting users and roles uses a primary key generated from a sequence, as opposed to a composite key. I can't really change this, because I'm writing it to be implemented in a larger existing system.
Here is my UserMap:
public UserMap()
{
this.Table("USR");[code].....
Yet, this is giving me the error:
Type 'FluentNHibernate.Cfg.FluentConfigurationException' in assembly 'FluentNHibernate, Version=1.0.0.593, Culture=neutral, PublicKeyToken=8aa435e3cb308880' is not marked as serializable.
Is there a simple fix to allow this HasMayToMany to use my PersistentObjectMap extension? I'm thinking I may have to add a convention for this many-to-many relationship, but I don't know where to start with that, since I've just started using NHibernate and Fluent NHibernate only recently.
EDIT: I think I've found a possible solution here: http://marekblotny.blogspot.com/2009/02/fluent-nhbernate-and-collections.html
I'll try the above method of creating an entity and a class map for the linking table and post my findings.
EDIT 2: I created a linking entity as mentioned in the above blog post and downloaded the newest binaries (1.0.0.623).
This helped me discover that the issue was with setting lazy load and trying to add roles to the user object in a completely new session.
I modified the code to move OpenSession to the BeginRequest of an HttpModule as described here. After doing this, I changed my data access code from wrapping the open session in a using statement, which closes the session when it is finished, to getting the current session and wrapping only the transaction in a using statement.
This seems to have resolved the bulk of my issue, but I am now getting an error that says "Could not insert collection" into the USR_ROLE table. And I'm wondering if the above code should work with a UserRoleMap described as:
public UserRoleMap()
{
this.Table("USR_ROLE"); [code]....
Hibernate's documentation for many-to-many relationship suggests creating an object to maintain a one-to-many/many-to-one, as in an ERD. I'm sure this would be much easier with conventional naming standards, but I have to stick with certain abbreviations and odd (and not always properly-implemented) conventions.
am trying to implement fluent nhibernate in MVC project...there were no build errors... but when i run the project i get this exception
System.Xml.Schema.XmlSchemaValidationException: The element 'class' in namespace 'urn:nhibernate-mapping-2.2' has incomplete content. List of possible elements expected: 'meta, subselect, cache, synchronize, comment, tuplizer, id, composite-id' in namespace 'urn:nhibernate-mapping-2.2'.
have no idea what am doing wrong here... the following is the code for opening session factory...
[code]....
How to configure Fluent NHibernate to output queries to Trace or Debug instead of Console?
I'm using MsSqlConfiguration.MsSql2008.ShowSql() but it has no parameters and I can't find anything on Google.
How can I write a unit test for CRUD using in memory database with fluent nhibernate
View 2 RepliesI am writing unit tests for fluent Nhibernate, when I run the test in isloation it passes, but when I run multiple tests. or run the test more than once it starts failing with the message below System.ApplicationException : For property 'Id' expected '1' of type 'System.Int32' but got '2' of type 'System.Int32'
[TextFixture]
public void Can_Correctly_Map_Entity()
{
new PersistenceSpecification<UserProfile>(Session)
.CheckProperty(c => c.Id, 1)
.CheckProperty(c => c.UserName, "user")
.CheckProperty(c => c.Address1, "Address1")
.CheckProperty(c => c.Address2, "Address2")
}
I'm building an application using MVC 3 and Entity Framework 4. I've created my Entity Data Model and generated a database from it. Now I know the validation attributes such as [Required] or [StringLength(5)] can be used on the model properties to provide validation both clientside and serverside.
I would like to know if these attributes can also be generated dynamically instead of having to add them to the model explicitly? I saw that in EF 4.1 RC you can make use of the Fluent API to further configure your model in the OnModelCreating method by using the DbModelBuilder class. As shown here I'm working with a framework however that still uses ObjectContext instead of DbContext so I would like to know if the above solution can be used in combination with ObjectContext?
As a final note, since I've been trying to figure out how to generate and use data annotations it seems using view models would increase the complexity of validation. From what I read here it seems that just passing the models directly to the view would remove the need to add annotations to the models as well as the view models. However that means that you can no longer use strongly typed views when you do joins on the models and pass those to the view directly?
In subsonic 2 we could do this:
public static void DeleteTable(SubSonic.TableSchema.Table table)
{
new Delete().From(table).Execute();
}
How can we do the same thing in v3? I can only seem to find documentation about using generics to target a specific table in the database...I want to be able to use it with a parameter as above.
Can you validate just a single property with the Fluent Validation Library, and if so how? I thought this discussion thread from January of 2009 showed me how to do it via the following syntax:
validator.Validate(new Person(), x => x.Surname);
Unfortunately it doesn't appear this works in the current version of the library. One other thing that led me to believe that validating a single property might be possible is the following quote from Jeremy Skinners' blog post:
"Finally, I added the ability to be able to execute some of FluentValidation's Property Validators without needing to validate the entire object. This means it is now possible to stop the default "A value was required" message from being added to ModelState. "
However I do not know if that necessarily means it supports just validating a single property or the fact that you can tell the validation library to stop validating after the first validation error.
public class OneControl
{
...
public OneControl Content(Action value) {
ContentProperty = value;
return this;
}
public void Render()
{
ContentProperty();
}
...
}
Then I got this in my view :
<div id="pleaseHelpMe">
<% OneControlInstance.Content(() => { %>
Some Mixed Stuff <%= Example%> Euros
<% }).Render() %>
</div>
I would like to use this syntax in my UI library, I know how to implement this but I don't know HOW it actually works! I understand that somewhere and somewhat a delegate is created and provided as an argument of the method Content, but can't find any information about this mecanism or technic. Assumed current correct answer : The compiler translates the aspx code below into (symbolic translation for comprehension):
<div id="pleaseHelpMe">
<% OneControlInstance.Content(() => {
ViewPageInstance.Response.Write("Some Mixed Stuff ");
ViewPageInstance.Response.Write(Example);
ViewPageInstance.Response.Write(" Euros");
}).Render() %>
</div>
I want to use NHibernate with Asp.net 3.5 but i don't know how to use it.I search on Google but couldn't find the complete explanation about why to use NHibernate,Advantages of using it and integration with Asp.net projects.
View 4 RepliesI am about to give up on this pos...unless somebody here simply gives me the right code to fix my problem. I'm tired of running in circles, and scouring the internet with no progress at all.
Problem: not updating collections with FK's.
Example:
Forum forum = new Forum("Sample");
category.AddForum(forum);
categoryRepository.Update(category); <- fails with transient object error for forum with no CategoryId.
Mapped right using References<Category> and HasMany<Forum>. Conventions are as follows.
Ref:
instance.Column(instance.Property.Name + "Id");
HasMany:
instance.Key.Column(instance.EntityType.Name + "Id");
instance.Cascade.All();
instance.Access.ReadOnlyPropertyThroughCamelCaseField(CamelCasePrefix.None);
Now, I've tried every possible setting for inverse, all the different cascades, on both sides. Nothing works. It just flat fails, telling me it can't insert NULL for Forum.CategoryId (field, not entity prop).
I've been reading up on DDD a little bit, and I am confused how this would fit in when using an ORM like NHibernate. Right now I have a .NET MVC application with fairly "fat" controllers, and I'm trying to figure out how best to fix that. Moving this business logic into the model layer would be the best way to do this, but I am unsure how one would do that.
My application is set up so that NHibernate's session is managed by an HttpModule (gets session / transaction out of my way), which is used by repositories that return the entity objects (Think S#arp arch... turns out a really duplicated a lot of their functionality in this). These repositories are used by DataServices, which right now are just wrappers around the Repositories (one-to-one mapping between them, e.g. UserDataService takes a UserRepository, or actually a Repository). These DataServices right now only ensure that data annotations decorating the entity classes are checked when saving / updating.
In this way, my entities are really just data objects, but do not contain any real logic. While I could put some things in the entity classes (e.g. an "Approve" method), when that action needs to do something like sending an e-mail, or touching other non-related objects, or, for instance, checking to see if there are any users that have the same e-mail before approving, etc., then the entity would need access to other repositories, etc. Injecting these with an IoC wouldn't work with NHibernate, so you'd have to use a factory pattern I'm assuming to get these. I don't see how you would mock those in tests though......................
I am using NHibernate in my web application. I need to use Convert() method in NHibernate query in order to get the date format as "MM/DD/YYYY".
I have used the below query using NHibernate query SELECT DISTINCT Convert(varchar(10),CurrentDate,101) AS Date FROM table order by Date desc.
But getting error.
Even I tried using views without unique key but Entity requires primary key.
I am working on NHibernate with oracle in ASP.Net. Now i am trying TDD(Test Driven Development). Can you tell me the best way to develop the TDD for NHibernate with oracle?I am using MbUnit with microdesk but it is not better approach for oracle but SQL server.
View 1 Replies