All my models contain at least two associations. When modeling this in ef4 I’ve only been able to do this without a second Foreign Key property through the use of the fluent interface. ForeignKey seems like the right attribute to use, except for the fact that it requires a string parameter.
So my question is, can you have a navigational property and declare it as such using an attribute?
public class User : IAuditable
{
// other code
public virtual User Creator { get; set; }
public virtual User Modifier { get; set; }
}
I believe, it is not possible to define the relationship only with data attributes. The problem is that EF’s mapping conventions assume that
CreatorandModifierare the two ends of one and the same relationship but cannot determine what the principal and what the dependent of this association is. As far as I can see in the list of supported attributes there is no option to define principal and dependent end with data annotations.Apart from that, I guess that you actually want two relationships, both with an end which isn’t exposed in the model. This means that your model is “unconventional” with respect to the mapping conventions. (I think a relationship between
CreatorandModifieris actually nonsense – from a semantic viewpoint.)So, in Fluent API, you want this:
Because a
Usercan be the Creator or Modifier of many other User records. Right?If you want to create these two relationships without Fluent API and only with DataAnnotations I think you have to introduce the Many-Ends of the associations into your model, like so:
I assume here that
CreatorandModifierare required, otherwise we can omit the[Required]attribute.I think it’s a clear case where using the Fluent API makes a lot of sense and is better than modifying the model just to avoid Fluent configuration.