我正在尝试首先将下面的模型(见下图)转换为代码。我尝试过涉及ForeignKey和InverseProperty属性的各种组合,但都没有成功。我已经找到了这个answer,但是ForeignKey和InverseProperty的组合似乎会导致不同的行为。
附加的源代码提供了以下错误:
无法确定类型'InversePropertyTest.Author‘和'InversePropertyTest.Book’之间关联的主端。必须使用关系fluent API或数据注释显式地配置此关联的主体端。
这是我的EDMX模型

样本代码:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InversePropertyTest
{
public class Author
{
public int AuthorId { get; set; }
public Nullable<int> CurrentlyWorkingBookId { get; set; }
[InverseProperty("Author")] public ICollection<Book> Books { get; set; }
[ForeignKey("CurrentlyWorkingBookId"), InverseProperty("EditoredBy")] public Book CurrentlyWorkingBook { get; set; }
}
public class Book
{
public int BookId { get; set; }
public int AuthorId { get; set; }
[ForeignKey("AuthorId"), InverseProperty("Books")] public Author Author { get; set; }
[InverseProperty("CurrentlyWorkingBook")] public Author EditoredBy { get; set; }
}
public class SimpleContext : DbContext
{
public DbSet<Author> Authors { get; set; }
public DbSet<Book> Books { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
class Program
{
static void Main(string[] args)
{
using (var context = new SimpleContext())
{
IList<Author> authors = (from a in context.Authors select a).ToList();
IList<Book> books = (from b in context.Books select b).ToList();
}
}
}
}任何帮助都是非常感谢的。
发布于 2013-10-31 16:16:18
当您在1:1关联的两端使用[InverseProperty]时,不清楚主体应该是谁。原则是另一端(受抚养人)通过外键所指的实体。尽管您告诉EF EditoredBy和CurrentlyWorkingBookId都是一个关联的一部分,但是仍然有可能在Book中为EditoredBy设置一个外键字段(这在类模型中不会显示)。
诚然,可以说您已经告诉EF足够正确地创建数据库模型了。EF可能有这样的逻辑:如果我在1:1的关联中被告知一个外键,那么我就知道原则应该是谁。但不幸的是,事实并非如此。
因此,我将使用fluent API对此进行建模:
public class Author
{
public int AuthorId { get; set; }
public ICollection<Book> Books { get; set; }
public Book CurrentlyWorkingBook { get; set; }
}
public class Book
{
public int BookId { get; set; }
public int AuthorId { get; set; }
public Author Author { get; set; }
public Author EditoredBy { get; set; }
}在OnModelCreating中
modelBuilder.Entity<Author>()
.HasMany(a => a.Books)
.WithRequired(b => b.Author)
.HasForeignKey(b => b.AuthorId);
modelBuilder.Entity<Author>()
.HasOptional(a => a.CurrentlyWorkingBook)
.WithOptionalDependent(b => b.EditoredBy)
.Map(m => m.MapKey("CurrentlyWorkingBookId"));就我个人而言,我喜欢fluent API,因为lambda表达式允许编译时检查,而且包含一个关联的结尾更加突出。
正如您所看到的,在这个场景中,CurrentlyWorkingBookId不能成为类模型的一部分。这是因为OptionalNavigationPropertyConfiguration (WithOptionalDependent的返回类型)没有HasForeignKey方法。我不知道为什么不。我认为应该可以设置原语FK值(CurrentlyWorkingBookId)和引用属性(CurrentlyWorkingBook)。
https://stackoverflow.com/questions/19701618
复制相似问题