【问题标题】:foreignkey column in object relation model in C#C#中对象关系模型中的外键列
【发布时间】:2011-10-22 12:46:57
【问题描述】:

为什么在ORM(对象关系模型)模型中,图书类中的外键列发布者是一个发布者类,而我们可以使用长类型(在数据库中发布者是外键和Bigint)?

public class Publisher 
{
    [XmlAttribute]
    public string Title { get; set; }
    [XmlAttribute]
    public string Address { get; set; }
}


public class Book 
{
    [XmlElement]
    public Publisher Publisher { get; set; }  ******
    [XmlAttribute]
    public string Title { get; set; }
    [XmlAttribute]
    public short PrintYear { get; set; }
    [XmlAttribute]
    public short Pages { get; set; }
    [XmlAttribute]
    public string ISBN { get; set; }
}

【问题讨论】:

    标签: c# asp.net object-relational-model


    【解决方案1】:

    这是为了让您的生活更轻松。在您的数据库中,表BOOK 有一个PublisherId,它是表PUBLISHER 的外键。为了避免像在 SQL 中那样在 C# 代码中编写关系连接,Book 类具有引用类型 Publisher 的属性,因此您可以直接访问它。这也更符合OOD原则。

    例子:

    如果您的班级Book 只有public int PublisherId {get;set;},则需要以下代码来获取发布者的Title

    Book book = ... 
    Publisher publisher = context.Publishers
                                 .Where(x => x.PublisherId == book.PublisherId)
                                 .SingleOrDefault();
    if(publisher != null)
        Console.WriteLine(publisher.Title);
    

    使用当前的Book 类,这更短且更易于阅读:

    Book book = ...
    Publisher publisher = book.Publisher;
    if(publisher != null)
        Console.WriteLine(publisher.Title);
    

    【讨论】:

      猜你喜欢
      • 2012-07-22
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多