Navigation Property without Declaring Foreign Key

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; }
}

Answers


I believe, it is not possible to define the relationship only with data attributes. The problem is that EF's mapping conventions assume that Creator and Modifier are 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 Creator and Modifier is actually nonsense - from a semantic viewpoint.)

So, in Fluent API, you want this:

modelBuilder.Entity<User>()
            .HasRequired(u => u.Creator)
            .WithMany();

modelBuilder.Entity<User>()
            .HasRequired(u => u.Modifier)
            .WithMany();

Because a User can 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:

public class User
{
    public int UserId { get; set; }

    [InverseProperty("Creator")]
    public virtual ICollection<User> CreatedUsers { get; set; }
    [InverseProperty("Modifier")]
    public virtual ICollection<User> ModifiedUsers { get; set; }

    [Required]
    public virtual User Creator { get; set; }
    [Required]
    public virtual User Modifier { get; set; }
}

I assume here that Creator and Modifier are 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.


Need Your Help

How to include version string in the filename when building Android apk with ant?

android ant version apk

Normally we build android package in debug mode with the command

GNU make differences in multiline variable declarations

variables makefile

I read this question, and I was surprised it wasn't working: