简体   繁体   English

代码优先6.0的一对多关系映射错误

[英]One to many relationship mapping error with code first 6.0

I have two entities Task and Attempt, One task has many Attempt, so I defined the entities as below. 我有两个实体Task和Attempt,一个任务有很多Attempt,因此我如下定义了实体。

public class Task
{
    public long TaskId { get; set; }
    [Required]
    public int DestinationNumber { get; set; }
    [Required]
    public int CountryCode { get; set; }
    // blah blah
    public virtual ICollection<Attempt> Attempts { get; set; }
}

public class Attempt
{
    public long Id { get; set; }
    public string AttemptsMetaData { get; set; }
    public DateTime Time { get; set; }
    public bool Answered { get; set; }
    public DateTime Disconnected { get; set; }
    // foreign key
    public long TaskId { get; set; }
    public virtual Task Task { get; set; }
}

I used Code First Relationships Fluent API to map the relationship. 我使用Code First Relationships Fluent API来映射关系。

public class OutboundContext : DbContext
{
    public DbSet<Task> Tasks { get; set; }
    public DbSet<Attempt> Attempts { get; set; }
    public OutboundContext()
        : base("Outbound")
    {
        Database.SetInitializer<OutboundContext>(new CreateDatabaseIfNotExists<OutboundContext>());
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Task>().HasMany(t => t.Attempts).WithRequired();
    }

Unit test was passed but when I check the table [Outbound].[dbo].[Attempts]. 通过了单元测试,但是当我检查表[Outbound]。[dbo]。[Attempts]时。 The columns are 列是

   [Id]
  ,[AttemptsMetaData]
  ,[Time]
  ,[Answered]
  ,[Disconnected]
  ,[Task_TaskId]
  ,[Task_TaskId1]

You see first [Task_TaskId] is wrong and one more extra column [Task_TaskId1] was generated. 您会看到第一个[Task_TaskId]错误,并且又生成了一个额外的列[Task_TaskId1]

What is wrong? 怎么了?

EDIT : 编辑

TaskId should be the foreign key. TaskId应该是外键。

// Add dummy data
        public bool AddAttempt(List<Attempt> attempt)
        {
            using (OutboundContext db = new OutboundContext())
            {
                foreach (var item in attempt)
                {
                    db.Attempts.Add(item);
                }
                try
                {
                    db.SaveChanges();
                    return true;
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return false;
                }
            }
        }

        List<Attempt> attempts = new List<Attempt>();
        Attempt objAtt = new Attempt();
        long id = 123456789;
        objAtt.AttemptId = id;
        objAtt.Time = DateTime.Now;
        objAtt.AttemptsMetaData = "test";
        objAtt.Answered = true;
        objAtt.Disconnected = DateTime.Now;
        objAtt.TaskId = 33333333;
        attempts.Add(objAtt);
        //Then call AddAttempt

It seems that the problem happened because the Collection of Attempt you have in the Task class is not being actually referenced to the "Task" property you are having in the Attempt class. 似乎发生了问题,是因为您在Task类中拥有的Attempt集合实际上并未被引用到您在Attempt类中拥有的“ Task”属性。 My suggestion is to clearly declare a int TaskId property in the Attempt class and do the mapping in the following way for Attempt Class: 我的建议是在Attempt类中明确声明一个int TaskId属性,并按以下方式对Attempt类进行映射:

HasRequired(attempt => attempt.Task)
            .WithMany(task => task.Attempts)
            .HasForeignKey(attempt => attempt.TaskId);

Hope this helps. 希望这可以帮助。

Using Fluent API. 使用Fluent API。

modelBuilder.Entity<Task>().HasMany(t => t.Attempts).WithRequired(t=>t.Task).HasForeignKey(t => t.TaskId);

The other point is that we have to save the tables in correct order. 另一点是我们必须以正确的顺序保存表。 Something like: 就像是:

            db.Tasks.Add(task);
            db.SaveChanges();
            Attempt a = new Attempt() { Id = Guid.NewGuid(), TaskId = task.TaskId, AttemptsMetaData = "1" };
            db.Attempts.Add(a);
            db.SaveChanges();

Otherwise it shows "invalid column" on TaskId in SQL Server Management Studio. 否则,它将在SQL Server Management Studio中的TaskId上显示“无效列”。

I made a very small change to the OnModelCreating and its not creating a an additional [Task_TaskId1] in the database: 我对OnModelCreating进行了非常小的更改,并且未在数据库中创建其他[Task_TaskId1]:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Task>().HasMany(t => t.Attempts);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM