Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

c# - One to one relationship with Entity Framework Fluent API

I'm having trouble with reverse navigation on one of my entities.

I have the following two objects:

public class Candidate
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long CandidateId { get; set; } 
    ....

    // Reverse navigation
    public virtual CandidateData Data { get; set; }
    ...

    // Foreign keys
    ....
}

public class CandidateData
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long CandidateDataId { get; set; }

    [Required]
    public long CandidateId { get; set; }

    // Foreign keys
    [ForeignKey("CandidateId")]
    public virtual Candidate Candidate { get; set; }
}

Now my foreign key navigation on the CandidateData object works fine. I am having trouble getting the reverse navigation for the candidate object to work (if that's even possible).

This is my OnModelCreating function:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

    modelBuilder.Entity<Candidate>()
        .HasOptional(obj => obj.Data)
        .WithOptionalPrincipal();

    base.OnModelCreating(modelBuilder);
}

It's close to working except in the database I get two columns that link to the CandidateId. I get the one I from the POCO object the I get another column Candidate_CandidateId I assume was created by the modelBuilder.

I am quiet lost at the moment. Can someone please shed some light on what's going on?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The One to One problem.... The issue is EF and CODE First, when 1:1 , for the dependent to have a Primary key that refers to the principal. ALthough you can define a DB otherwise and indeed with a DB you can even have OPTIONAL FK on the Primary. EF makes this restriction in Code first. Fair Enough I think...

TRy this instead: IS have added a few opinions on the way which you may ignore if you disagree:-)

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace EF_DEMO
{
class FK121
{
    public static void ENTRYfk121(string[] args)
    {
        var ctx = new Context121();
        ctx.Database.Create();
        System.Console.ReadKey();
    }
}
public class Candidate
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]// best in Fluent API, In my opinion..
    public long CandidateId { get; set; }
 //   public long CandidateDataId { get; set; }// DONT TRY THIS... Although DB will support EF cant deal with 1:1 and both as FKs
    public virtual CandidateData Data { get; set; }  // Reverse navigation

}
public class CandidateData 
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] // best in Fluent API as it is EF/DB related 
    public long CandidateDataId { get; set; }   // is also a Foreign with EF and 1:1 when this is dependent
   // [Required]
   // public long CandidateId { get; set; }   // dont need this... PK is the FK to Principal in 1:1
   public virtual Candidate Candidate { get; set; } // yes we need this
}
public class Context121 : DbContext
{
    static Context121()
    {
        Database.SetInitializer(new DropCreateDatabaseIfModelChanges<Context121>());
    }
    public Context121()
        : base("Name=Demo") { }
    public DbSet<Candidate> Candidates { get; set; }
    public DbSet<CandidateData> CandidateDatas { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Candidate>();

        modelBuilder.Entity<CandidateData>()
                    .HasRequired(q => q.Candidate)
                    .WithOptional(p=>p.Data) // this would be blank if reverse validation wasnt used, but here it is used
                    .Map(t => t.MapKey("CandidateId"));    // Only use MAP when the Foreign Key Attributes NOT annotated as attributes
    }
}

}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...