0

我创建了一个新闻模型。我的新闻有一位作者属于会员类别。这足以设置外键吗?

 HasRequired(n => n.Author);

代码:

public class Member : Identity
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public Address Address { get; set; }
    public int Id { get; set; }

    public virtual ICollection<News> News { get; set; }

}

public class News
{
    public string Title { get; set; }
    public string Subtile { get; set; }
    public int Id { get; set; }
    public string Url { get; set; }
    public DateTime DateAdded { get; set; }


    public virtual Member Author;

}
public class NewsMap : EntityTypeConfiguration<News>
{
    public NewsMap()
    {

        HasKey(n => n.Id);
        Property(n => n.Id).
            HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
            .HasColumnName("Id");

        Property(t => t.Title)
            .IsRequired()
            .HasMaxLength(100)
            .IsUnicode();
        Property(t => t.Subtile)
            .IsRequired()
            .HasMaxLength(100)
            .IsUnicode();
        Property(t => t.Url)
            .IsRequired()
            .HasMaxLength(255)
            .IsUnicode();
        Property(t => t.DateAdded).HasColumnName("DateAdded")
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);

        HasRequired(n => n.Author); //is this enough for the foreing key to be set?



    }

}
public class MemberMap : EntityTypeConfiguration<Member>
{
    public MemberMap()
    {
        // Primary Key
        this.HasKey(t => t.Id);

        // Properties
        this.Property(t => t.FirstName)
            .IsRequired()
            .HasMaxLength(150);

        this.Property(t => t.LastName)
            .IsRequired()
            .HasMaxLength(50);

        this.Property(t => t.Email)
            .IsRequired()
            .HasMaxLength(150);

        this.Property(t => t.Address.Id)
            .IsRequired()
            .HasMaxLength(100)
            .HasColumnName("Address_FirstLine");

        this.Property(t => t.Address.ZipCode)
            .IsRequired()
            .HasMaxLength(20).HasColumnName("Address_Zip");

        this.Property(t => t.Address.Contry)
            .IsRequired()
            .HasMaxLength(100).HasColumnName("Address_Contry");

        this.Property(t => t.Address.City)
            .IsRequired()
            .HasMaxLength(100).HasColumnName("Address_Town");

        this.Property(t => t.Id);


        // Table & Column Mappings
        this.ToTable("Identities_Member");
        this.Property(t => t.FirstName).HasColumnName("FirstName");
        this.Property(t => t.LastName).HasColumnName("LastName");
        this.Property(t => t.Email).HasColumnName("Email");
        this.Property(t => t.Id).HasColumnName("Id");

        // Relationships



    }
}
4

1 回答 1

0

感谢@Gert 的回答

那还不够。实在是太多了。嗯,严格来说。FK 甚至会在没有HasRequired. 有了它,FK 将不能为空。

于 2012-10-01T19:54:08.047 回答