English 中文(简体)
How to map and test a "Many to Many Relationship" in NHibernate using Fluent NHibernate
原标题:

When I test my many to many classes an error occurs:

System.ApplicationException: Actual count does not equal expected count.

Entities:

    public interface IEntity
    {
        int Id { get; set; }
    }

    public abstract class Entity : IEntity
    {
        public virtual int Id { get; set; }

        public virtual bool IsPersistent
        {
            get { return isPersistentObject(); }
        }

        public override bool Equals(object obj)
        {
            if (isPersistentObject())
            {
                var persistentObject = obj as Entity;
                return (persistentObject != null) && (Id == persistentObject.Id);
            }

            return base.Equals(obj);
        }

        public override int GetHashCode()
        {
            return isPersistentObject() ? Id.GetHashCode() : base.GetHashCode();
        }

        private bool isPersistentObject()
        {
            return (Id != 0);
        }
    }

    public class Team : Entity
    {
        public virtual string Name { get; set; }
        public virtual ISet<Employee> Employees { get; set; }

        public Team()
        {
            Employees = new HashedSet<Employee>();
        }
    }

    public class Employee : Entity
    {
        public virtual string LastName { get; set; }
        public virtual string FirstName { get; set; }
        public virtual ISet<Team> Teams { get; set; }
        public virtual string EMail { get; set; }

        public Employee()
        {
            Teams = new HashedSet<Team>();
        }
    }

Mappings:

public class TeamMap : ClassMap<Team>
{
    public TeamMap()
    {
        // identity mapping
        Id(p => p.Id).Column("TeamID");

        // column mapping
        Map(p => p.Name);

        // relationship mapping
        HasManyToMany(m => m.Employees)
            .Table("EmployeeTeam")
            .LazyLoad()
            .Cascade.SaveUpdate()
            .AsSet()
            .ParentKeyColumn("TeamID")
            .ChildKeyColumn("EmployeeID");
    }
}

public class EmployeeMap : ClassMap<Employee>
{
    public EmployeeMap()
    {
        // identifier mapping
        Id(p => p.Id).Column("EmployeeID");

        // column mapping
        Map(p => p.EMail);
        Map(p => p.LastName);
        Map(p => p.FirstName);

        // relationship mapping
        HasManyToMany(m => m.Teams).Table("EmployeeTeam")
            .Inverse()
            .Cascade.SaveUpdate()
            .AsSet()
            .LazyLoad()
            .ParentKeyColumn("EmployeeID")
            .ChildKeyColumn("TeamID");
    }
}

Test:

[TestMethod]
public  void  CanCorrectlyMapEmployee()
{
    var team = new List<Team> {new Team() {Name = "Team1"}};

    new PersistenceSpecification<Employee>(_session)
        .CheckProperty(p => p.EMail, "Mail")
        .CheckProperty(p => p.FirstName, "Firstname")
        .CheckProperty(p => p.Id, 1)
        .CheckProperty(p => p.LastName, "Lastname")
        .CheckList(p => p.Teams,team )
        .VerifyTheMappings();
}

Whether I add an Employee or a Team my EmployeeTeam table is always empty.

I have tested it against SQLLite with FNH and manually against SQL Server 2008.

Does anybody of you have an idea to fix this?

edit:

I was amazed to find out that when I create an Employee and add 2 Teams to the Employee and load the created Employee he has 2 Teams. So it works fine. But when I look in my relationsip table EmployeeTeam then everything is empty. Can someone explain me why?

And does anybody know how I can use Fluent NHibernate to test my many to many relationship?

Thanks in advance!

最佳回答

Employee map has inverse attribute. As you probably know, this means that when you save employee, relationship table (EmployeeTeam) will not be updated. To add/remove new relationship information you have to add employee to the Team and save Team.

So, in your case - don t test many to many on the side of employee, test it on the side of team. (If you d like NHibernate to add records when you add team to employee, you ll have to invert "Inverse" attributes - give it to team, not employee, but then - same story with Team entity).

Why were you able to load Employee with teams? Because of session-level cache. You ve probably saved and loaded Employee in the same ISession - this means that NHibernate returned you exactly reference to the same object, without loading it from the db. Try saving & loading in two different sessions and you ll see no team in Employee.Teams set.

Side note: It is considered a good practice to create methods that will enforce consistency between many-to-many relationships, that is - when you add Team to Employee, Employee is added to the team, sth. like this:

class Employee 
{
  // ...
  public void AddTeam(Team team)
  {
     // check for null, etc. 

     Teams.Add(team);
     team.Employees.Add(this);
  }
}

and very simillar method in the Team class.

问题回答

暂无回答




相关问题
run unit tests and coverage in certain python structure

I have some funny noob problem. I try to run unit tests from commandline: H:PROpyEstimator>python src estpython est_power_estimator.py Traceback (most recent call last): File "src est...

How to unit-test an enterprise symfony project?

I´m working on a huge project at my work. We have about 200 database tables, accordingly a huge number of Models, Actions and so on. How should I begin to write tests for this? My biggest problem ...

Code Coverage Tools & Visual Studio 2008 Pro

Just wondering what people are using for code coverage tools when using MS Visual Studio 2008 Pro. We are using the built-in MS test project and unit testing tool (the one that come pre-installed ...

Unit testing. File structure

I have a C++ legacy codebase with 10-15 applications, all sharing several components. While setting up unittests for both shared components and for applications themselves, I was wondering if there ...

Unit Testing .NET 3.5 projects using MStest in VS2010

There s a bug/feature in Visual Studio 2010 where you can t create a unit test project with the 2.0 CLR. https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=483891&wa=...

Unit Test for Exceptions Message

Is there a simple (Attribute-driven) way to have the following test fail on the message of the exception. [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void ExceptionTestTest() ...

热门标签