开发者

How to map my class to get the db's records with a custom method?

I'm developing a website with ASP.NET MVC, NHibernate and Fluent NHibernate and want to know how can I customize my Map to get records using a custom Method.

My entities:

public class ImageGallery {
    public virtual int Id { get; set; }
    public virtual string Titulo { get; set; }
    public virtual IList<Image> Images { get; set; }
    public virtual bool IsActive { get; set; }
}
public class Image {
    public virtual int Id { get; set; }
    public virtual开发者_如何学编程 ImageGallery ImageGallery { get; set; }
    public virtual string Low { get; set; }
    public virtual bool IsActive { get; set; }
}

My Fluent NHibernate Maps:

public class ImageGalleryMap:ClassMap<ImageGallery> {
    public ImageGalleryMap() {
        Id(x => x.Id);
        Map(x => x.Titulo);
        HasMany(x => x.Images)
            .KeyColumn("ImageGalleryID");
        Map(x => x.IsActive);
    }
}
public class ImageMap:ClassMap<Image> {
    public ImageMap() {
        Id(x => x.Id);
        References(x => x.ImageGallery);
        Map(x => x.Low);
        Map(x => x.IsActive);
    }
}

And, a method on my ImageRepository class:

    public IList<Image> ListActive() {
        return this.Session.CreateCriteria<Image>()
                           .Add(Restrictions.Eq("IsActive", true))
                   .List<Image>();
    }

If I create an object this way:

ImageGallery ig = new ImageGallery();

I can access my the Image's list using:

foreach(Image img in ig.Images) {
   ...
}

However, ig.Images give me access to all images records and I would like to access just active records (or another criteria), using ListActive()'s repository methods.

How can I specify this on my Map?

Thank you very much!


A Where constraint in the mapping will limit the Images to active ones always:

public class ImageMap:ClassMap<Image> {
    public ImageMap() {
        Id(x => x.Id);
        References(x => x.ImageGallery);
        Map(x => x.Low);
        Map(x => x.IsActive);
        Where("IsActive = 1");
    }
}

If you want to load the Images collection but dynamically filter it for active records, the best way is to create an extension method:

public static IEnumerable<Image> Active(this IEnumerable<Image> images)
{
    return images.Where(x => x.IsActive);
}

Then you can access the active records like this:

foreach(Image img in ig.Images.Active()) {
   ...
}

I like the extension method solution because it can be used on any IEnumerable<Image>, not just the collection on ImageGallery. I would definitely use this solution unless loading inactive images was a measurable performance problem.

If you want to selectively load active Images only then start by reading this article about NHibernate Filters because I don't have any experience with them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜