使用Fluent API将EF属性与Shadow属性作为键的一对一关系

时间:2019-02-05 14:04:02

标签: c# entity-framework-core

我无法使用“阴影属性”作为键来解决两个类之间的一对一关系。不幸的是,由于使用了3​​rd party类库,因此无法在类中创建真正的键属性。

using Microsoft.EntityFrameworkCore;
using System;

namespace EFCoreTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Create database");
            using (var context = new ClassDbContext())
            {
                if (!context.Database.EnsureDeleted())
                {
                    Console.WriteLine(" => Can't delete database");
                }
                if (context.Database.EnsureCreated())
                {
                    context.SaveChanges();
                    Console.WriteLine(" => Done");
                }
                else
                {
                    Console.WriteLine(" => Can't create database");
                }
            }
            Console.WriteLine("End");
        }
    }
    public class ClassDbContext : DbContext
    {
        public virtual DbSet<ClassA> ClassA { get; set; }
        public virtual DbSet<ClassB> ClassB { get; set; }
        public ClassDbContext()
        {
        }
        public ClassDbContext(DbContextOptions<ClassDbContext> options) : base(options)
        {
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer("Server=XXX.XXX.XXX.XXX;Database=XXXXX;User ID=XXXXX;Password=XXXXX");
            }
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<ClassA>().Property<int>("ClassAId");
            modelBuilder.Entity<ClassB>().Property<int>("ClassBId");
            modelBuilder.Entity<ClassB>().Property<int>("AnotherClassId");
            modelBuilder.Entity<ClassB>().HasOne(p => p.AnotherClass).WithMany().HasForeignKey("AnotherClassId");
        }
    }
    public class ClassA
    {
        public string PropertyA { get; set; }
    }
    public class ClassB
    {
        public string PropertyB { get; set; }
        public ClassA AnotherClass { get; set; }
    }
}

EF Core返回并显示以下错误,这让我非常困惑:

  

System.InvalidOperationException :具有外键属性的“从ClassB.AnotherClass”到“ ClassA”的关系   {'AnotherClassId': int }无法定位主键{'ClassAId'   : int } ,因为它不兼容。配置主键   或与此关系相关的一组兼容外键属性。'

1 个答案:

答案 0 :(得分:1)

事实证明,通过属性命名在EF Core中实现的将属性自动绑定到键在这种情况下不起作用

他们要求您在创建连接之前先输入密钥名称!

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ClassA>().Property<int>("ClassAId");
    modelBuilder.Entity<ClassA>().HasKey("ClassAId"); // <=== This is a SOLUTION
    modelBuilder.Entity<ClassB>().Property<int>("ClassBId");
    modelBuilder.Entity<ClassB>().Property<int>("AnotherClassId");
    modelBuilder.Entity<ClassB>().HasOne(p => p.AnotherClass).WithMany().HasForeignKey("AnotherClassId");
}