开发者

foreignkey column in object relation model in C#

why in ORM(object relation model) Mode开发者_如何学Cl in this sample foreignkey column publisher in book class is a class of publisher,while where we could use of a long type(in database publisher is foreignkey and 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; }
}


This is to make your life easier. In your database the table BOOK has a PublisherId that is a foreign key to the table PUBLISHER. To avoid the need to write relational joins in your C# code as you need to do in SQL, your Book class has a property of the referenced type Publisher, so you can directly access it. This also conforms more to OOD principles.

Example:

If your class Book only had a public int PublisherId {get;set;}, you would need the following code to get the publisher's Title:

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

With the current Book class, this is shorter and easier to read:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜