繁体   English   中英

尝试使用 EF Core 在 FOREIGN KEY 中插入 INT 时,为什么会出现“无法将类型 'int' 隐式转换为用户”?

[英]Why do I get “Cannot implicitly convert type 'int' to User” when trying to insert an INT in FOREIGN KEY using EF Core?

我在 .NET Core Winforms 应用程序中使用 EF Core。 我想插入一个 INT 作为外键,但出现错误

  namespace FTAS
    {
   public partial class SecurityQuestion : Form
        {
   
    public user users;
    
    
    public SecurityQuestion(LoginForm loginForm, user userdata)
    {
        InitializeComponent();
        this.users = userdata;
        
        
    }
   
    private void BtnSubmitQuestion_Click(object sender, EventArgs e)
    {

        if (IsValid())
        {
            var context = new FtasDbContext();

            context.SQuestion.Add(new Entity.SQuestions
            {
                Question = Questioncombo.Text,
                Answer = TxtQuestionAns.Text,
                User = users.Id

            }) ;

            context.SaveChanges();

        }

    }

   

    private bool IsValid()
    {
        if (Questioncombo.Text == string.Empty)
        {
            return false;
        }
        else
      if (TxtQuestionAns.Text.Trim() == string.Empty)
        {
            return false;
        }
        else
            return true;
    }

}
}

但这是 Table User INT的核心

 namespace FTAS.Entity
 {
    [Table("User")]
   public class user
{
    public int Id { get; set; }


    public string Name { get; set; }


    public string FatherName { get; set; }


    public long Cnic { get; set; }


    public string Gender { get; set; }

    public long Mob { get; set; }

   


    public string Email { get; set; }


    public string Username { get; set; }


    public string Password { get; set; }


    public string Designation { get; set; }    


    public DateTime DateOfBirth { get; set; }

  
    
}
    
}

那为什么我得到错误CS0029 无法将类型“int”隐式转换为“FTAS.Entity.user”

我也在尝试
私人用户 int32(int id) { throw new NotImplementedException(); 并更改用户 = int32(users.Id)

然后我得到错误

'该方法或操作未实现。

Entity.SQuestion 的代码

  class SQuestions
  {
    public long Id { get; set; }

    public string Question { get; set; }


    public string Answer { get; set; }
   
    public user User { get; set; }

    
    }
}

class SQuestions 中的属性 User 是“user”类型,与 users.Id 类型不同,后者是 int 类型。 作业必须属于同一类型。

改变:

User = users.Id

至:

User = users

在此代码命名空间 FTAS.Entity { class SQuestions { public long Id { get; 放; }

    public string Question { get; set; }


    public string Answer { get; set; }
   
    public user User { get; set; }
    
   }
  }

改变

public user User { get; set; }

public user User { get; set; } 
[ForeignKey("User")]
public int UserFK { get; set; }

并解决了问题

暂无
暂无

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

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