实体框架代码第一种方法 - 一对一的关系

时间:2012-09-13 19:38:07

标签: c# asp.net-mvc entity-framework ef-code-first

我的模特协会(我相信)是一对一的:

public class Account
{
    [Key]
    [ForeignKey("BlockedAccount")]
    public virtual Guid AccountId { get; set; }
    public virtual string UserName { get; set; }

    public virtual BlockedAccount BlockedAccount { get; set; }
}

public class BlockedAccount
{
    [Key]
    public virtual Guid BlockedAccountId { get; set; }
    public virtual int BanLevel { get; set; }
    public virtual DateTime BannedDate { get; set; }
    public virtual DateTime ExpirationDate { get; set; }
    public virtual string Reason { get; set; }
}

但是当我尝试使用它时,程序崩溃了,它给了我以下异常:

  

INSERT语句与FOREIGN KEY约束冲突   “FK_dbo.Accounts_dbo.BlockedAccounts_AccountId”。冲突发生了   在数据库“Accounts”中,表“dbo.BlockedAccounts”,列   'BlockedAccountId'。声明已经终止。

我在这里做错了什么?我希望AccountId指向BlockedAccountId

1 个答案:

答案 0 :(得分:1)

您如何附加您的实体?您不需要实际设置外键,只需附加到导航属性即可进行连接。以上模型的代码适用于我:

     public class Account
{
    [Key]
    [ForeignKey("BlockedAccount")]
    public virtual Guid AccountId { get; set; }
    public virtual string UserName { get; set; }

    public virtual BlockedAccount BlockedAccount { get; set; }
}

public class BlockedAccount
{
    [Key]
    public virtual Guid BlockedAccountId { get; set; }
    public virtual int BanLevel { get; set; }
    public virtual DateTime BannedDate { get; set; }
    public virtual DateTime ExpirationDate { get; set; }
    public virtual string Reason { get; set; }

    public BlockedAccount()
    {
        BannedDate = DateTime.Now;
        ExpirationDate = DateTime.Now;
    }
}

public class Model : DbContext
{
    public DbSet<BlockedAccount> BlockedAccounts { get; set; }
    public DbSet<Account> Accounts { get; set; }
}
class Program
{

    static void Main(string[] args)
    {
        var b = new BlockedAccount()
            {
               BlockedAccountId = Guid.NewGuid()
            };
        var a = new Account();

        a.BlockedAccount = b;
        Model m = new Model();
        m.Accounts.Add(a);
        m.SaveChanges();
    }
}

enter image description here