不知道如何为列表设置实体

时间:2015-10-06 14:12:12

标签: entity-framework

我有一个用户

public class UserEntity
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int Id { get; set; }

    [Index(IsUnique=true)]
    [Required, StringLength(50)]
    public string Username { get; set; }

    public List<UserTokenEntity> Tokens { get; set; }
}

有一个令牌列表,我不知道如何设置它,以便在生成迁移时UserEntityId的键不为null。这是我的TokenEntity

public class UserTokenEntity
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [StringLength(512)]
    [Required]
    public string TokenHash { get; set; }

    [StringLength(128)]
    [Required]
    public string Device { get; set; }
}

当我为这些实体添加迁移时,会为令牌实体上的数据库创建UserEntity_Id,但它是nullable int,我希望nullablefalse

这是生成的迁移

 public override void Up()
    {
        CreateTable(
            "dbo.UserTokenEntities",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    TokenHash = c.String(nullable: false, maxLength: 512),
                    Device = c.String(nullable: false, maxLength: 128),
                    UserEntity_Id = c.Int(),
                })
            .PrimaryKey(t => t.Id)
            .ForeignKey("dbo.UserEntities", t => t.UserEntity_Id)
            .Index(t => t.UserEntity_Id);)
    }

是否有人知道如何设置令牌实体以使UserEntity_Id成为nullable: false而无需手动更改?

1 个答案:

答案 0 :(得分:2)

您可以明确定义关系:

public class UserTokenEntity
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [StringLength(512)]
    [Required]
    public string TokenHash { get; set; }

    [StringLength(128)]
    [Required]
    public string Device { get; set; }

    public int UserEntityId { get; set; }
    [ForeignKey("UserEntityId")]
    public UserEntity UserEntity { get; set; }

}

https://msdn.microsoft.com/en-us/data/jj591583.aspx#Relationships