NHibernate:分配外键

时间:2011-07-19 20:23:00

标签: c# nhibernate fluent-nhibernate

我正在尝试分配外键但收到错误。这是我的代码:

public class User : Entity
{
    public User()
    {
        WebSite = new List<WebSite>();
    }

    public virtual string Name { get; set; }
    public virtual IList<WebSite> WebSite { get; set; }

    public virtual void AddWebSite(WebSite ws)
    {
        ws.User = this;
        WebSite.Add(ws);
    }
}


public class WebSite : Entity
{
    public WebSite()
    {
        Setup();
    }

    public WebSite(string Url)
    {
        DomainUrl = Url;
        Setup();
    }

    private void Setup()
    {
        WebPage = new List<WebPage>();
        User = new User();
    }

    public virtual string DomainUrl { get; set; }
    public virtual bool IsApproved { get; set; }
    public virtual User User { get; set; }

    public virtual IList<WebPage> WebPage { get; set; }
}


public class WebSiteMap : ClassMap<WebSite>
{
    public WebSiteMap()
    {
        Id(x => x.Id).Not.Nullable();
        Map(x => x.DomainUrl).Length(3000).Not.Nullable();
        Map(x => x.IsApproved).Not.Nullable();
        References(x => x.User).Column("UserId").Nullable();
        HasMany(x => x.WebPage).AsBag().Inverse();
    }
}


public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Id(x => x.Id).Not.Nullable().GeneratedBy.Assigned();
        Map(x => x.Name).Not.Nullable().Length(2000);
        HasMany(x => x.WebSite).Inverse().AsBag();
    }
}


Uri u = new Uri("http://yahoo.com");
WebSite ws = new WebSite(u.Host);
ws.IsApproved = true;

var CurrentSession = MvcApplication10.MvcApplication.SessionFactory;
using (var session = CurrentSession.OpenSession())
{
     using (var tx = session.BeginTransaction())
     {
          session.Save(ws);
          tx.Commit();
     }
}

用户是网站的父级。用户可以拥有许多网站。在代码中,我试图插入一个没有用户的网站。因此,用户外键可以为空。

当我运行代码时,我收到此错误:

无法更新:[TheSite.WebSite#23] [SQL:UPDATE WebSite SET DomainUrl = ?, IsApproved = ?, UserId =?在哪里Id =?]

现在出现奇怪的事情

当我在事务外部使用插入时,它可以工作。这是我用来完成这项工作的代码

 using (var session = CurrentSession.OpenSession())
 {
      session.Save(ws);
      using (var tx = session.BeginTransaction())
      {   
            //tx.Commit();
      }
  }

我将session.Save(ws)从事务中删除然后它工作了。这是为什么?

0 个答案:

没有答案