1

Let's say we have this

class A
{
    [Key]
    public int Id { get; set; }
    public string X { get; set; }
    public string Y { get; set; }
    public B B;
}

class B
{
    [Key]
    public int Id { get; set; }
    public string X { get; set; }
    public string Y { get; set; }
    public virtual ICollection<A> As { get; set; }
}

Assume that pairs of X and Y are guaranteed to be unique in B, thus {X, Y} could be a composite primary key on B but isn't, Id is.

Is it possible with Fluent API to express that A.B should be a navigation property via this fake foreign key relationship?

Something like this, except it doesn't work:

HasRequired(a => a.B).WithMany(b => b.As).HasForeignKey(a => new { a.X, a.Y })
4

1 回答 1

0

You said you wanted 'fake' foreign keys, and I'm not sure if that means you don't want your database to reflect the relationship. If that's the case, then you don't want to express this in fluent, you should enforce this in your business logic. If you do want a true foreign key, then you'll need to alter the primary key of B, and then make the composite foreign key attachment. There's a typo in your initial class of A, you didn't create the navigation property B as a property. I assume these aren't your real objects though, but I was able to get this to work like this:

 public class A
    {
        public int Id { get; set; }
        public string X { get; set; }
        public string Y { get; set; }
        public virtual B B { get; set; }
    }

public class B
{
    public int Id { get; set; }
    public string X { get; set; }
    public string Y { get; set; }
    public virtual ICollection<A> As { get; set; }
}

public class Model : DbContext
{
    public DbSet<A> As { get; set; }
    public DbSet<B> Bs { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Entity<B>()
            .HasKey(b => new { b.Id, b.X, b.Y });

        modelBuilder.Entity<A>()
            .HasRequired(a => a.B)
            .WithMany(b => b.As)
            .HasForeignKey(a => new { a.Id, a.X, a.Y });
    }
}
于 2012-08-16T14:34:40.367 回答