سؤال

I am using Fluent NHibernate and NHibernate.Core 3 beta 1. I have two classes:

public class Promotion
{
    public Promotion()
    {
        PromotionEntrants = new List<PromotionEntrant>();
    }

    public virtual int Id { get; set; }        
    [Required]
    public virtual string Name { get; set; }
    ...
    public virtual IList<PromotionEntrant> PromotionEntrants { get; set; }
}

public class PromotionEntrant
{
    public virtual int Id { get; set; }
    ...
    public virtual Promotion Promotion { get; set; }
}

I am using auto mapping, which generates the schema I expect and things seem to be working as expected for the most part.

I have the following action (ASP.NET MVC 3 RC) for saving/creating Promotions:

[HttpPost]
public ActionResult SavePromo(Promotion promo)
{
    if (ModelState.IsValid)
    {
        // .SaveOrUpdateCopy(promo) results in the same SQL
        NhSession.SaveOrUpdate(promo);
        NhSession.Flush();
    }

    ...
}

This executes the expected "update Promotion ..." query, however it also executes the following:

UPDATE [PromotionEntrant] SET PromotionId = null WHERE PromotionId = @p0;@p0 = 1 [Type: Int32 (0)]

How do I prevent this from happening?

My only guess is that it is seeing the empty List on the Promotion object (constructed by ASP.NET MVC thus not attached to the NH Session), taking that to mean there should be no child PromotionEntrants. To try and prevent that, I created the following auto-mapping override, but it does not make a difference.

public class PromotionMappingOverride : IAutoMappingOverride<Promotion>
{
    public void Override(AutoMapping<Promotion> mapping)
    {
        mapping.HasMany(p => p.PromotionEntrants)
            .Cascade.None();
    }
}

Any help would be much appreciated.

هل كانت مفيدة؟

المحلول

Verify that PromotionEntrant.Promotion actually points back to the promotion. Given that this is a bidirectional relationship, the relationship is managed from the child side of the relationship. From the parent side, you'll have an inverse=true collection.

BTW - You really should be running your code in a transaction. If you are already, the NhSession.Flush() is superfluous.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top