dan_l
dan_l

Reputation: 1692

asp.net mvc with NHibernate - how to handle many-to-one when saving/creating entity

I have a entity called Worker , and another entity called Company. In the NHibernate mapping of Worker .. I say

<many-to-one name="Company" column="CompanyID"/>

The classes are

public class Company 
{
   public virtual int Id {get; set;}
   public virtual string Name { get; set;}
}
public class Worker
{
   public virtual int Id {get; set;}
   public virtual Company Company { get; set;}
   public virtual CompanyID { get { return Company == null ? 0 : Company.Id;}}
}

In my view for creating Worker I have html form that has a CompanyID input . How to handle creat/update of worker properly in my controller after the user submit the form with a html POST ? The CompanyID field is read only. How to make TryValidate TryUpdateModel in this case ?

Upvotes: 0

Views: 407

Answers (2)

Felice Pollano
Felice Pollano

Reputation: 33252

You should not use the ID when you are using an ORM. Do something like session.Get<Company>(id) to retrieve te correct company entity and assign it to the property Company of your Worker entity. I will even remove the CompanyID property from your class.

Upvotes: 0

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

I don't know ASP.NET and the whole stuff, but I can tell you how you should implement it against NHibernate.

You need to pass the properties of the worker including the CompanyID to the server. I suggest to use a DTO instead of passing the entity.

If you need more details, you should explain how you transfer these data to the server.

//create a company-proxy. this doesn't touch the database
Company company = session.Load<Company>(companyId);
// assign it the the worker. You need to put the worker into the 
// session somehow before. this depends on your specific server interface
worker.Company = company;

Upvotes: 2

Related Questions