如何使用非身份主列保存实体?

时间:2014-07-22 13:39:58

标签: c# asp.net-mvc entity

我有一个会员班:

[Table("members")]
public partial class Member
{
    [Key]
    public Int64 id { get; set; }
    public String email { get; set; }
    public String password { get; set; }
    public String lang { get; set; }
    public Boolean activated { get; set; }
    public String gender { get; set; }
    public String first_name { get; set; }
    public String middle_name { get; set; }
    public String last_name { get; set; }
}

和member_activation类:

[Table("member_activation")]
public class MemberActivation
{
    [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public Int64 member_id { get; set; }
    public String token { get; set; }
}

member_activation.member_id是members.id的外键。

这是我的DbContext:

public class SMADbContext : DbContext
{
    public SMADbContext() : base("SMADB")
    {
        Database.SetInitializer<SMADbContext>(new NullDatabaseInitializer<SMADbContext>());
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }

    public DbSet<Member> Members { get; set; }
    public DbSet<MemberActivation> MemberActivations { get; set; }
}

当我尝试...

public bool tester()
    {
        var db = new SMADbContext();
        var memberActivation = new MemberActivation();
        memberActivation.member_id = 10150;
        memberActivation.token = "hello";
        db.MemberActivations.Add(memberActivation);
        if(db.SaveChanges())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

我收到一条错误消息:

  

无法将值NULL插入列&#39; member_id&#39;,table&#39; dbname.dbo.member_activation&#39;;列不允许空值。 INSERT失败。\ r \ n语句已终止。

有人知道我可以保存member_activation行吗?

1 个答案:

答案 0 :(得分:0)

如果您的查询是“如何使用非身份主列保存实体?”。

然后回答是你做不到的。表(实体)中必须有主键。

但实际上在你的代码中,我可以看到密钥。