I am new to .net mvc. I am trying to create a model with a one to one relationship to another model.
I’d like to be able to display read only info on the edit pages for each model about its one to one relation.
Here is my code:
public class Thing1 : BaseEntity
{
public virtual Thing2 thing2 { get; set; }
[Required(ErrorMessage = "This field is required.")]
public int Thing2ID { get; set; }
... Other basic fields go here
}
public class Thing2 : BaseEntity
{
...basic fields
}
The basic fields stand for just regular non-relational fields.
Now with this model, it is easy to display Thing2 data on the Thing1 form, but how do I display the Thing1 data on the Thing2 form? Is there something that I add to the Thing2 model to link it to thing1?
Background: I am using mvc3 with entity code first and razor.
Probably the easiest thing to do would be to add a new property to Thing2 for the relationship ,thus making it a bi-directional one-to-one relationship
e.g.
Then, you need to make sure that Thing 1 and Thing 2 don’t get out of sync. You could do this something like:
(Excuse typo’s, but you get the idea)
That way, you can go
Thing1.SetThing2(myThing2)(and vice versa) and both properties will be set.Without that kind of set-up (ie making the properties read-only, and making a convenience method to set both properties at once) you risk the objects getting out of sync with each other – so a Thing1 might reference a Thing2 without that Thing2 referencing Thing1.