Nhibernate Criterion - select rows in table A of TypeId defined in Table B
the title is confusing sorry, if you can think of a better one, please change it.
I have three tables, say, bikes, owners and a relationship table (something like many to many) that defines all owners of a bike, or all bikes of an owner.
So, I want to select All bikes of OwnerId 1 But, my mapping i开发者_Go百科s like so:
BikeOwners references one Bike
BikeOwners References one OWner
How do I write the criterion in nhibernate to do this?
Right now, I am trying:
DetachedCriteria crit = DetachedCriteria.For<Bikes>()
.Add(Expression.Eq("OwnerId", _ownerId));
and it errors out saying there isn't any OwnerId
in Bikes table, which I understand..
Hope the question is clear.. If you need any details, please ask!
I know I can get first get a list of all Bike id's from
Bike owner
table and then use that int array to get all bikes in bikes
table - BUT - it is two database access and I am doing it manually, there should be a way to do this in one go, right?
This is my plan b, if all else fails, I'll do this.
Thanks
It really depends on your entities. I have mocked up a sample entity, just adopt it to yours.
public class Bike
{
public int BikeId;
public IList<BikeOwners> BikeOwners;
public string BikeName;
}
public class Owners
{
public int OwnerId;
public IList<BikeOwners> OwnersBikes;
public string OwnerName;
}
public class BikeOwners
{
public int Id;
public Owners owner;
public Bikes bike;
}
Now, you are going to write your nhibernate criteria like this:
DetachedCriteria crit = DetachedCriteria.For<Bikes>()
.CreateCriteria("BikeOwners") //from Bikes class
.CreateCriteria("owner") // from BikeOwners class
.Add(Expression.Eq("OwnerId", _OwnerId)); //from Owners class
obviously, you need to modify it to your entities and names.
Unless there's more column in the BikeOwners table, it shouldn't be represented in the domain model at all. Bike and Owner should be mapped as a many-to-many relationship. Also, I find it unusual that a Bike can have multiple Owners.
精彩评论