开发者

Should I be making References in Fluent Nhibernate Not Nullable?

I have something like this in my Map

public class Settings : ClassMap<Setting>
{
  References(x => x.User).Not.Nullable();
}

Now every time I want to save a settings I have to give it a User Object otherwise I get

not-null property references a null or transient value

My thinking was that by doi开发者_如何转开发ng this I will enforce relational constraints. However it just seems weird that I have to pass in the whole object when really it needs to just use the Fk.

I hope it is not re-saving the whole thing internally and just adding the Fk to keep relational constraints.

So am I do this the right way?

Edit

 public class Settings : ClassMap<Setting>
 {
      Id(x => x.SettingId);
      Map(x => x.Something);
      Map(x => x.Something2);
      References(x => x.User).Not.Nullable();
 }


Public class User: ClassMap<User>
{
   Id(x => x.UserId);
   Map(x => x.FirstName);
   Map(x => x.LastName);
   HasOne(x => x.Settings);
   HasMany(x => x.AnotherTable);
}


Settings s = new Settings()
{
      Something = "142",
      Something2 = "1421414"
};

session.Create(s); // this will crash as s.User equals null;

I have to do this

User user = repo.GetUser("userId");

Settings s = new Settings()
{
      Something = "142",
      Something2 = "1421414",
      User = user
};

session.Create(s); // this should work.

Now I am wondering since I did User = user; Does nhibernate just grab the userId and save that into the Settings tbl or does it go through and check the user table for changes, and then checks the "another table" for changes?

Or does it do a blink update of all the fields for the user table and the another table.

Does that make sort of sense of what I mean by is it saving the whole object?


You are telling NHibernate to validate this property for nulls by using .Not.Nullable().

Of course it will complain if it's null, with an appropriate message.

If you want it to be nullable... just don't tell it otherwise :-)

Update: I'm still have problems understanding what your concern is. If you retrieve a User instance (actually, you don't even have to go to the DB if you have the Id; just use session.Load) and do not change any properties, why would NHibernate "resave" it?


No, it won't resave/update the user object. It will only get it's Id and update the Fk Column. If you wan't to know what is happening behind the scenes, you try using SQL Server Profiler (if your DB is MSSQL) or the NHibernate Profiler.

By the way, check this ayende's post, it tells about different ways of save/update/delete cascades in NHibernate.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜