我具有以下ERD,并希望将其转换为EF 4.1 Code First类。为了简单起见,我将仅关注前两个实体。
作者>引用。
这是为我的实体提供代码的正确方法,this:
public class Quote
{
public int Id { get; set; }
[Required, MaxLength(500)]
public string Body { get; set; }
public int Likes { get; set; }
[Required]
public bool isApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public int AuthorId { get; set; }
public int LanguageId { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
public class Author
{
public int Id { get; set; }
[Required, MaxLength(30), MinLength(2)]
public string FirstName { get; set; }
[Required, MaxLength(30), MinLength(2)]
public string LastName { get; set; }
[Required]
public DateTime DOB { get; set; }
public DateTime DOD { get; set; }
[Required, MaxLength(60), MinLength(2)]
public string Occupation { get; set; }
[Required, MaxLength(170), MinLength(5)]
public string WikiLink { get; set; }
public byte[] Image { get; set; }
[Required]
public bool isApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public virtual ICollection<Quote> Quotes { get; set; }
}
在为每个Quote赋予了一个Integer类型的属性的地方,它表示作者和语言的ID 或此:
public class Quote
{
public int Id { get; set; }
[Required, MaxLength(500)]
public string Body { get; set; }
public int Likes { get; set; }
[Required]
public bool isApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public Author Author { get; set; }
public Language Language { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
public class Author
{
public int Id { get; set; }
[Required, MaxLength(30), MinLength(2)]
public string FirstName { get; set; }
[Required, MaxLength(30), MinLength(2)]
public string LastName { get; set; }
[Required]
public DateTime DOB { get; set; }
public DateTime DOD { get; set; }
[Required, MaxLength(60), MinLength(2)]
public string Occupation { get; set; }
[Required, MaxLength(170), MinLength(5)]
public string WikiLink { get; set; }
public byte[] Image { get; set; }
[Required]
public bool isApproved { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public virtual ICollection<Quote> Quotes { get; set; }
}
每个报价都具有类型作者的属性和类型语言的属性。
第一个例子很罕见。您在不使用导航属性的情况下公开外部属性=您在公开数据库的特定功能,但不使用面向对象的功能。
第二个例子很常见,甚至还有第三种可能的方式,使Quote实体同时具有FK和导航属性。这将使difference between independent and foreign key associations。