我想在C_中,在多对多关系中执行LINQ到SQL的映射,但在这种情况下,数据不是必需的。
清楚:
我有一个新闻网站/博客,还有一个叫做
Posts
. 一个博客可以同时关联多个类别,因此有一个名为
CategoriesPosts
与外国钥匙的联系
帖子
表与
Categories
表。我用一个身份主键和一个
id
每个字段中的字段,如果在本例中很重要。
在C中,我为每个表定义了一个类,尽可能明确地定义了每个字段。这个
Post
以及
Category
上课,有一个
EntitySet
链接到
CategoryPost
对象,以及
分类帖子
班级有2人
EntityRef
要链接到彼此类型的2个对象的成员。
问题是,一个职位可能与任何类别相关,也可能与某个类别相关,或者不相关。我找不到方法
EntitySet<CategoryPost?>
或者类似的。
因此,当我添加第一篇文章时,没有一条SQL语句,一切都很顺利。此外,这篇文章也出现在输出中。当我试图添加第二个帖子时,我得到了一个例外,
对象引用未设置为对象的实例
,关于
分类帖子
成员。
职位:
[Table(Name="tm_posts")]
public class Post : IDataErrorInfo
{
public Post()
{
//Initialization of NOT NULL fields with their default values
}
[Column(Name = "id", DbType = "int", CanBeNull = false, IsDbGenerated = true, IsPrimaryKey = true)]
public int ID { get; set; }
private EntitySet<CategoryPost> _categoryRef = new EntitySet<CategoryPost>();
[Association(Name = "tm_rel_categories_posts_fk2", IsForeignKey = true, Storage = "_categoryRef", ThisKey = "ID", OtherKey = "PostID")]
public EntitySet<CategoryPost> CategoryRef
{
get { return _categoryRef; }
set { _categoryRef.Assign(value); }
}
}
分类帖子
[Table(Name = "tm_rel_categories_posts")]
public class CategoryPost
{
[Column(Name = "id", DbType = "int", CanBeNull = false, IsDbGenerated = true, IsPrimaryKey = true)]
public int ID { get; set; }
[Column(Name = "fk_post", DbType = "int", CanBeNull = false)]
public int PostID { get; set; }
[Column(Name = "fk_category", DbType = "int", CanBeNull = false)]
public int CategoryID { get; set; }
private EntityRef<Post> _post = new EntityRef<Post>();
[Association(Name = "tm_rel_categories_posts_fk2", IsForeignKey = true, Storage = "_post", ThisKey = "PostID", OtherKey = "ID")]
public Post Post
{
get { return _post.Entity; }
set { _post.Entity = value; }
}
private EntityRef<Category> _category = new EntityRef<Category>();
[Association(Name = "tm_rel_categories_posts_fk", IsForeignKey = true, Storage = "_category", ThisKey = "CategoryID", OtherKey = "ID")]
public Category Category
{
get { return _category.Entity; }
set { _category.Entity = value; }
}
}
类别
[Table(Name="tm_categories")]
public class Category
{
[Column(Name = "id", DbType = "int", CanBeNull = false, IsDbGenerated = true, IsPrimaryKey = true)]
public int ID { get; set; }
[Column(Name = "fk_parent", DbType = "int", CanBeNull = true)]
public int ParentID { get; set; }
private EntityRef<Category> _parent = new EntityRef<Category>();
[Association(Name = "tm_posts_fk2", IsForeignKey = true, Storage = "_parent", ThisKey = "ParentID", OtherKey = "ID")]
public Category Parent
{
get { return _parent.Entity; }
set { _parent.Entity = value; }
}
[Column(Name = "name", DbType = "varchar(100)", CanBeNull = false)]
public string Name { get; set; }
}
我做错了什么?如何使插入不属于任何类别的文章成为可能?如何插入没有文章的类别?