【问题标题】:Entity Framework 5 Code First - Non-Nullable Foriegn Key FieldsEntity Framework 5 Code First - 不可为空的外键字段
【发布时间】:2013-08-07 02:34:54
【问题描述】:

我是 Entity Framework 的新手,即将开始使用 EF5 Code First 的新 ASP.NET MVC 项目。

我在试用 EF 时注意到,在我的数据库中为我自动生成的外键字段允许 NULL,我想知道我如何在代码中配置内容,以便它不允许这些字段为空?

示例(为简洁而编辑):

public class Shop
{
    int Id { get; set; }
    string Name { get; set;

    // Navigation Property.
    Certificate Certificate { get; set; } // ******
}

public class Certificate
{
    int Id { get; set; }
    string Descrip { get; set; }
}

我突出显示的导航属性会自动在数据库的 Shop 表中生成一个字段,称为 Certificate_Id,但它允许 NULL,我想指定它不应允许 NULL。

如何使用 Fluent API 做到这一点?

【问题讨论】:

    标签: asp.net entity-framework ef-code-first entity-framework-5 fluent


    【解决方案1】:

    试试这个:

    public class Shop
    {
        int Id { get; set; }
        string Name { get; set; }
    
        [Required]
        int CertId { get; set; }
    
        // Navigation Property.
        [ForeignKey("CertId")]
        Certificate Certificate { get; set; } // ******
    }
    
    public class Certificate
    {
        int Id { get; set; }
        string Descrip { get; set; }
    }
    

    【讨论】:

      【解决方案2】:

      试试这样:

      public class TempContext : DbContext
      {
          public DbSet<Shop> Shops { get; set; }
          public DbSet<Certificate> Certificates { get; set; }
      
          protected override void OnModelCreating(DbModelBuilder modelBuilder)
          {
              modelBuilder.Entity<Shop>().HasRequired(x => x.Certificate);
          }
      }
      

      【讨论】:

        【解决方案3】:

        您可以根据需要使用Required 属性来标记属性。

        MSDN

        这是你的例子:

        public class Shop
        {
            int Id { get; set; }
            string Name { get; set;
        
            [Required]
            Certificate Certificate { get; set; }
        }
        

        Here是对不同注解的解释。

        【讨论】:

          猜你喜欢
          • 2023-04-11
          • 1970-01-01
          • 2015-09-18
          • 2015-06-25
          • 1970-01-01
          • 2015-08-31
          • 1970-01-01
          • 2015-04-12
          • 1970-01-01
          相关资源
          最近更新 更多