.net mvc3 one to one
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 开发者_C百科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.
public class Thing2 : BaseEntity
{
public virtual Thing2 Thing2 { get; set; }
...basic fields
}
Then, you need to make sure that Thing 1 and Thing 2 don't get out of sync. You could do this something like:
public class Thing1 : BaseEntity
{
private Thing2 thing2;
public virtual Thing2 Thing2 { get { return thing2; } }
public void SetThing2(Thing2 thing2)
{
this.thing2 = thing2;
thing2.SetThing1(this);
}
}
public class Thing2 : BaseEntity
{
private Thing1 thing1;
public virtual Thing1 Thing1 { get { return thing1; } }
public void SetThing1(Thing1 thing1)
{
this.thing1 = thing1;
thing1.SetThing2(this);
}
}
(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.
精彩评论