开发者

Persistance of 2 one-to-many with NHibernate

开发者 https://www.devze.com 2023-03-26 07:57 出处:网络
I have the following code which uses th开发者_开发知识库e repository pattern, backed by a fluent nhibernate automapping to a MySQL DB.

I have the following code which uses th开发者_开发知识库e repository pattern, backed by a fluent nhibernate automapping to a MySQL DB.

The following snippet adds a user, and a person to the model, and then persists to the database.

It works, however I have to remember to put user.Person.User = user; otherwise when the object is persisted, Person has the FK userId set to null.

  1. Is there a way to automatically cause the Person.User to be populated, or do I need to create a method to do this?

  2. Is there a way to cause all objects associated with that user to be persisted (e.g. only call repository.Save(obj) on one object and cause the others to also be persisted.)

        using (MySQLRepositoryBase repository = new MySQLRepositoryBase())
        {
            try
            {
                repository.BeginTransaction();
    
                User user = new User() { Password = "12345", Username = "jbloggs", Person = new Person() };
                user.Person.Firstname = "Joe";
                user.Person.Lastname = "Bloggs";
                user.Person.User = user;
    
                repository.Save(user);
                repository.Save(user.Person);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                repository.RollbackTransaction();
            }
        }
    


  1. NHibernate can't set this automatically, you have to do it yourself. Most common is a AddSomething() method in the parent entity which adds the child to the collection and sets the parent reference in the child. But if you don't need the parent reference in your code you could just remove it (and map only the collection).

  2. Use the Cascade options that are available on collections and references.

0

精彩评论

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