我有一个用 Enitity Framework 描述的简单数据模型,但仍然无法解决我的模型中的关系问题。我尝试了一些使用 Fluent API 的方法,但总是遇到非描述性异常。
这是一个代码:
public abstract class Entity
{
[Key, Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Int32 Id { get; set; }
}
public class Language : Entity
{
[Key, Column(Order = 2)]
public String Verbal { get; set; }
public virtual ICollection<PostContent> Contents { get; set; }
}
public class Post : Entity
{
public virtual ICollection<PostContent> Contents { get; set; }
}
public class PostContent
{
[Key, Column(Order = 1)]
public Int32 PostId { get; set; }
[Key, Column(Order = 2)]
public Int32 LanguageId { get; set; }
[ForeignKey("PostId")]
public virtual Post Post { get; set; }
[ForeignKey("LanguageId")]
public virtual Language Language { get; set; }
public String Content { get; set; }
}
public class BlogContext : DbContext
{
public DbSet<Language> Languages { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<PostContent> PostContents { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
public class BlogContextInitializer : DropCreateDatabaseIfModelChanges<BlogContext>
{
protected override void Seed(BlogContext context)
{
//For test
context.Languages.Add(new Language { Verbal = "Italian" });
context.Languages.Add(new Language { Verbal = "English" });
context.SaveChanges();
}
}
class Program
{
static void Main(string[] args)
{
Database.SetInitializer<BlogContext>(new BlogContextInitializer());
using (BlogContext blogContext = new BlogContext())
{
//init on call.
var langs = blogContext.Set<Language>().AsEnumerable();
foreach (var lang in langs)
{
Console.WriteLine("Language Id: {0}, Verbal: {1}", lang.Id, lang.Verbal);
}
}
}
}
我有:
“关系约束中的从属角色和主要角色中的属性数量必须相同。”
所以我正在寻找这个问题的解决方案。