简化示例:我有以下POCO:
public class Blog
{
public int Id {get;set;}
}
public class Post
{
public int Id {get;set;}
public int BlogId {get;set;}
}
如何阻止Entity Framework(Code First)推断Post.BlogId上的外键关系到Blog.Id?
这是一个非常简单的例子,但有一个很好的理由我不想在我的真实世界的例子中推断出FK。
答案 0 :(得分:0)
实际上,在您的示例中不会推断出Post.BlogId与Blog.Id的FK关系! ;)
要获取代码的FK,它应显示为:
public class Blog
{
public int Id { get; set; }
public ICollection<Post> Posts { get; set; } // This forces FK
}
public class Post
{
public int Id { get; set; }
public int BlogId { get; set; } // Optional (changes default column name Blog_Id to BlogId)
}
或
public class Blog
{
public int Id { get; set; }
}
public class Post
{
public int Id { get; set; }
public Blog Blog { get; set; } // This forces FK
public int BlogId { get; set; } // Optional (changes default column name Blog_Id to BlogId)
}
或
public class Blog
{
public int Id { get; set; }
public ICollection<Post> Posts { get; set; } // This forces FK
}
public class Post
{
public int Id { get; set; }
public Blog Blog { get; set; } // This forces FK
public int BlogId { get; set; } // Optional (changes default column name Blog_Id to BlogId)
}