获取错误:' Id'物业'匹配'无法设置为System.Int32'值

时间:2015-07-13 13:34:31

标签: c# entity-framework asp.net-web-api2

我收到了这个错误:

  

' Id'物业'匹配'无法设置为System.Int32'   值。您必须将此属性设置为类型的非null值   ' System.Int64&#39 ;. "

使用以下代码段:

Match _match =_entities.Match.SingleOrDefualt(match => match.Id == MatchId);

有时并非总是发生这种情况,我用数据库检查我的poco类的类型,这是正确的! 我先使用EF 6.1.3代码。我很困惑!

我的实体类是:

[Table("Match")]
public class Match
{
    public Match()
    {
        Hands = new HashSet<Hand>();
        Rounds = new HashSet<Round>();
    }

    public long Id { get; set; }

    public DateTime CreationDate { get; set; }

    public long FirstPlayerId { get; set; }

    public byte FirstPlayerRedrawHandCount { get; set; }

    public long? SecondPlayerId { get; set; }

    public byte SecondPlayerRedrawHandCount { get; set; }

    public byte SpeedType { get; set; }

    public MatchType MatchType { get; set; }

    public byte FirstPlayerScore { get; set; }

    public byte SecondPlayerScore { get; set; }

    public MatchStatus Status { get; set; }

    public long? DCUser { get; set; }

    public DateTime? RetryTime { get; set; }

    [Timestamp]
    public byte[] RowVersion { get; set; }

    public RegisterState RegisterState { get; set; }

    [ForeignKey("FirstPlayerId")]
    public virtual User User { get; set; }
    [ForeignKey("SecondPlayerId")]
    public virtual User User1 { get; set; }

    public virtual ICollection<Hand> Hands { get; set; }

    public virtual ICollection<Round> Rounds { get; set; }
}

2 个答案:

答案 0 :(得分:1)

从消息中,几乎可以确定您的表具有类型为System.int32(int)的Id,并且您的类具有system.int64(long)类型。

如果数据库字段为int(这里必须是这种情况),则将Match.Id更改为int。

答案 1 :(得分:0)

根据@Nikhil Agrawal的建议,将您的MatchId转换为ToInt64

Match _match =_entities.Match.SingleOrDefualt(match => match.Id == Convert.ToInt64(MatchId));

与.net一样,long和Int64相同