我在嘗試將以下模型(請參見下圖)轉換爲Code First。我嘗試過涉及ForeignKey和InverseProperty屬性的各種組合,但都沒有運氣。我發現這個answer,但似乎ForeignKey和InverseProperty的組合導致不同的行爲。EF5 InverseProperty問題
附帶的源代碼提供了以下錯誤:
Unable to determine the principal end of an association between the types 'InversePropertyTest.Author' and 'InversePropertyTest.Book'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
這是我與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();
}
}
}
}
任何幫助是極大的讚賞
感謝您的解釋,這正是我需要:) – dna2