Accept Interface into Collection (Covariance) trou

2019-03-06 14:29发布

问题:

I am using Fluent nHibernate for my persistence layer in an ASP.NET MVC application, and I have come across a bit of a quandry.

I have a situation where I need to use an abstraction to store objects into a collection, in this situation, an interface is the most logical choice if you are looking at a pure C# perspective.

Basically, an object (Item) can have Requirements. A requirement can be many things. In a native C# situation, I would merely accomplish this with the following code.

interface IRequirement
{
 // methods and properties neccessary for evaluation
}

class Item
{
 virtual int Id { get; set; }
 virtual IList<IRequirement> Requirements { get; set; }
}

A crude example. This works fine in native C# - however because the objects have to be stored in a database, it becomes a bit more complicated than that. Each object that implements IRequirement could be a completely different kind of object. Since nHibernate (or any other ORM that I have discovered) cannot really understand how to serialize an interface, I cannot think of, for the life of me, how to approach this scenario. I mean, I understand the problem.

This makes no sense to the database/orm. I understand completely why, too.

class SomeKindOfObject
{
 virtual int Id { get; set; }
 // ... some other methods relative to this base type
}
class OneRequirement : SomeKindOfObject, IRequirement
{
 virtual string Name { get; set; }
 // some more methods and properties
}
class AnotherKindOfObject
{
 virtual int Id { get; set; }
 // ... more methods and properties, different from SomeKindOfObject
}
class AnotherRequirement : AnotherKindOfObject, IRequirement
{
 // yet more methods and properties relative to AnotherKindOfObject's intentive hierarchy
}

class OneRequirementMap : ClassMap<OneRequirement>
{
 // etc
 Table("OneRequirement");
}
class AnotherRequirementMap : ClassMap<AnotherRequirement>
{
 //
 Table("OtherRequirements");
}
class ItemMap : ClassMap<Item>
{
 // ... Now we have a problem.
 Map( x => x.Requirements ) // does not compute... 
 // additional mapping
}

So, does anyone have any ideas? I cannot seem to use generics, either, so making a basic Requirement<T> type seems out. I mean the code works and runs, but the ORM cannot grasp it. I realize what I am asking here is probably impossible, but all I can do is ask.

I would also like to add, I do not have much experience with nHibernate, only Fluent nHibernate, but I have been made aware that both communities are very good and so I am tagging this as both. But my mapping at present is 100% 'fluent'.

Edit

I actually discovered Programming to interfaces while mapping with Fluent NHibernate that touches on this a bit, but I'm still not sure it is applicable to my scenario. Any help is appreciated.

UPDATE (02/02/2011)

I'm adding this update in response to some of the answers posted, as my results are ... a little awkward.

Taking the advice, and doing more research, I've designed a basic interface.

interface IRequirement
{
 // ... Same as it always was
}

and now I establish my class mapping..

class IRequirementMap : ClassMap<IRequirement>
{
 public IRequirementMap()
 {
    Id( x => x.Id );
    UseUnionSubclassForInheritanceMapping();
    Table("Requirements");
 }
}

And then I map something that implements it. This is where it gets very freaky.

class ObjectThatImplementsRequirementMap : ClassMap<ObjectThatImplementsRequirement>
{
 ObjectThatImplementsRequirementMap()
 {
  Id(x => x.Id); // Yes, I am base-class mapping it.
  // other properties
  Table("ObjectImplementingRequirement");
 }
}

class AnotherObjectThatHasRequirementMap : ClassMap<AnotherObjectThatHasRequirement>
    {
     AnotherObjectThatHasRequirementMap ()
     {
      Id(x => x.Id); // Yes, I am base-class mapping it.
      // other properties
      Table("AnotheObjectImplementingRequirement");
     }
}

This is not what people have suggested, but it was my first approach. Though I did it because I got some very freaky results. Results that really make no sense to me.

It Actually Works... Sort Of Running the following code yields unanticipated results.

// setup ISession
// setup Transaction
var requirements = new <IRequirement>
{
 new ObjectThatImplementsRequirement
 {
  // properties, etc.. 
 },
 new AnotherObjectThatHasRequirement
 {
  // other properties.
 }
}
// add to session.
// commit transaction.
// close writing block.

// setup new session
// setup new transaction
var requireables = session.Query<IRequirable>();
foreach(var requireable in requireables)
   Console.WriteLine( requireable.Id );

Now things get freaky. I get the results...

1 1

This makes no sense to me. It shouldn't work. I can even query the individual properties of each object, and they have retained their type. Even if I run the insertion, close the application, then run the retrieval (so as to avoid the possibility of caching), they still have the right types. But the following does not work.

class SomethingThatHasRequireables
{ 
 // ...
 public virtual IList<IRequirement> Requirements { get; set; }
}

Trying to add to that collection fails (as I expect it to). Here is why I am confused.

  • If I can add to the generic IList<IRequirement> in my session, why not in an object?
  • How is nHibernate understanding the difference between two entities with the same Id, if they are both mapped as the same kind of object, in one scenario, and not the other?

Can someone explain to me what in the world is going on here?

The suggested approach is to use SubclassMap<T>, however the problem with that is the number of identities, and the size of the table. I am concerned about scalability and performance if multiple objects (up to about 8) are referencing identities from one table. Can someone give me some insight on this one specifically?

回答1:

Take a look at the chapter Inheritance mapping in the reference documentation. In the chapter Limitations you can see what's possible with which mapping strategy.

You've chose one of the "table per concrete class" strategies, as far as I can see. You may need <one-to-many> with inverse=true or <many-to-any> to map it.

If you want to avoid this, you need to map IRequirement as a base class into a table, then it is possible to have foreign keys to that table. Doing so you turn it into a "table per class-hierarchy" or "table per subclass" mapping. This is of course not possible if another base class is already mapped. E.g. SomeKindOfObject.


Edit: some more information about <one-to-many> with inverse=true and <many-to-any>.

When you use <one-to-many>, the foreign key is actually in the requirement tables pointing back to the Item. This works well so far, NH unions all the requirement tables to find all the items in the list. Inverse is required because it forces you to have a reference from the requirement to the Item, which is used by NH to build the foreign key.

<many-to-any> is even more flexible. It stores the list in an additional link table. This table has three columns:

  • the foreign key to the Item,
  • the name of the actual requirement type (.NET type or entity name)
  • and the primary key of the requirement (which can't be a foreign key, because it could point to different tables).

When NH reads this table, it knows from the type information (and the corresponding requirement mapping) in which other tables the requirements are. This is how any-types work.

That it is actually a many-to-many relation shouldn't bother you, it only means that it stores the relation in an additional table which is technically able to link a requirement to more then one item.


Edit 2: freaky results:

You mapped 3 tables: IRequirement, ObjectThatImplementsRequirement, AnotherObjectThatHasRequirement. They are all completely independent. You are still on "table per concrete class with implicit polymorphism". You just added another table with containing IRequirements, which may also result in some ambiguity when NH tries to find the correct table.

Of course you get 1, 1 as result. The have independent tables and therefore independent ids which both start with 1.

The part that works: NHibernate is able to find all the objects implementing an interface in the whole database when you query for it. Try session.CreateQuery("from object") and you get the whole database.

The part that doesn't work: On the other side, you can't get an object just by id and interface or object. So session.Get<object>(1) doesn't work, because there are many objects with id 1. The same problem is with the list. And there are some more problems there, for instance the fact that with implicit polymorphism, there is no foreign key specified which points from every type implementing IRequirement to the Item.

The any types: This is where the any type mapping comes in. Any types are stored with additional type information in the database and that's done by the <many-to-any> mapping which stores the foreign key and type information in an additional table. With this additional type information NH is able to find the table where the record is stored in.

The freaky results: Consider that NH needs to find both ways, from the object to a single table and from the record to a single class. So be careful when mapping both the interface and the concrete classes independently. It could happen that NH uses one or the other table depending on which way you access the data. This may have been the cause or your freaky results.

The other solution: Using any of the other inheritance mapping strategies, you define a single table where NH can start reading and finding the type.

The Id Scope: If you are using Int32 as id, you can create 1 record each second for 68 years until you run out of ids. If this is not enough, just switch to long, you'll get ... probably more then the database is able to store in the next few thousand years...