1

为什么在 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; }
}
4

1 回答 1

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);
于 2011-08-08T16:05:49.290 回答