我有一张表'Article'
private int id;
[ColumnAttribute(Storage = "id", AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)]
public int Id
{
get { return id; }
set { id = value; }
}
private string title;
[ColumnAttribute(Storage = "title", DbType = "NVarChar(250) NOT NULL", CanBeNull = false)]
public string Title
{
get { return title; }
set { title = value; }
}
private string description;
[ColumnAttribute(Storage = "description", DbType = "NVarChar(350) NOT NULL", CanBeNull = false)]
public string Description
{
get { return description; }
set { description = value; }
}
和表评论
[Table(Name = "dbo.Comments")]
public class CommentDto
{
private int id;
[ColumnAttribute(Storage = "id", AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)]
public int Id
{
get { return id; }
set { id = value; }
}
private string content;
[ColumnAttribute(Storage = "content", DbType = "NVarChar(600) NOT NULL", CanBeNull = false)]
public string Content
{
get { return content; }
set { content = value; }
}
private string date;
[ColumnAttribute(Storage = "date", DbType = "DateTime NOT NULL", CanBeNull = false)]
public string Date
{
get { return date; }
set { date = value; }
}
}
一篇文章可以有很多评论,每个评论都可以由用户放置
[TableAttribute(Name = "dbo.Users")]
public class UserDto
{
private int id;
[ColumnAttribute(Storage = "id", AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)]
public int Id
{
get { return id; }
set { id = value; }
}
private string username;
[ColumnAttribute(Storage = "username", DbType = "NVarChar(150) NOT NULL", CanBeNull = false)]
public string Username
{
get { return username; }
set { username = value; }
}
如何映射这些表之间的关系?
由于
答案 0 :(得分:0)
我认为您是手动创建表类。没有必要这样做。
将LINQ to SQL(dbml)文件添加到您的解决方案中,打开“服务器资源管理器”窗口并连接到您的数据库, 将表拖放到dbml类的设计中。
如果表中存在外键约束,则链接将在两个类中创建相应的属性。
如果你想手动完成(我不明白为什么), 使用引用类的类型创建一个属性,这是所需的属性:
[Association(Name="your_fk_constraint_name", Storage="name_of_your_private_backup_field", ThisKey="name_of_the_key_in_this_table", IsForeignKey=true)]
希望我能帮助一点
答案 1 :(得分:0)
您可以阅读有关映射关联here的信息。
在你的情况下:
class Article
{
private EntitySet<CommentDto> _Comments;
[Association(OtherKey = "ArticleID")]
public virtual IList<CommentDto> Comments
{
get
{
if (_Comments == null)
_Comments = new EntitySet<CommentDto>();
return _Comments;
}
set
{
Comments.Assign(value);
}
}
}
class Comment
{
[Association(ThisKey="ArticleID")]
public ArticleDto Article { get; set; }
}
当然,您应首先将ArticleID列添加到数据库中的“注释”表。
以下部分未在上面链接的MSDN代码中显示,但没有它我在WCF服务中遇到了很多DTO问题。所以,现在我更愿意将它添加到每个协会:
if (_Comments == null)
_Comments = new EntitySet<CommentDto>();