代码首先是外键冲突

时间:2016-04-29 17:25:12

标签: c# .net sql-server ef-code-first

这是我的两个简化实体

public class Team
{
    public int TeamId { get; set; }

    public string Name { get; set; }

    public User User { get; set; }

    public int UserId { get; set; }
}

团队实体配置:

HasRequired(t => t.User)
           .WithOptional(u => u.Team);

用户类:

public class User
{
    public int UserId { get; set; }

    public string Username { get; set; }

    public Team Team { get; set; }

    public int TeamId { get; set; }
}

我制作了一个简单的演示控制台应用程序,它将用户插入到db然后获取它的主键以确保外键是数据库。

static void Main(string[] args)
    {   
        var test = new InsertTest();
        var userId = test.InsertUser();
        test.InsertTeam(userId);
    }
public int InsertUser()
    {
        var user = new User();
        user.Username = "test1";
        user.Email = "aaa@mail.hr";
        user.Name = "test";
        user.LastName = "Test";
        user.Password = "123";
        user.ConfirmPassword = "123";
        UnitOfWork.UseRepository.Insert(user);
        UnitOfWork.Save();

        var userdB = UnitOfWork.UseRepository.Get().Where(u => u.Name == "test").FirstOrDefault();

        return userdB.UserId;
    }

 public void InsertTeam(int userId)
    {
        var team = new Team();

        team.Name = "Test";
        team.UserId = userId;

        UnitOfWork.TeamRepository.Insert(team);
        UnitOfWork.Save();
    }

但是在数据库中插入团队时仍然会出现外键冲突。真的不知道下一步该做什么

例外是: INSERT语句与FOREIGN KEY约束“FK_dbo.Teams_dbo.Users_TeamId”冲突。冲突发生在数据库“Fantasy”,表“dbo.Users”,列“UserId”中。 声明已经终止。

1 个答案:

答案 0 :(得分:0)

将您的团队实体配置更改为

HasOptional(c => c.User)
            .WithRequired(c => c.Team)
            .Map(m => m.MapKey("_field"));

您可能还需要更改

public User User { get; set; } and
public Team Team { get; set; }

public virtual User User { get; set; } and
public virtual Team Team { get; set; }