我很抱歉,如果已经回答,但我找不到任何解决方案。这是我的(小)问题。如果我使用的术语是近似的,我也很抱歉,我远非熟练的C#开发人员
请注意,我认为我的问题类似于Entity Framework validation error for missing field, but it's not missing?
我有一个表“推文”,其中包含tweet_id字段(bigint),这是我的主键。
我使用以下类加载表:
class TwitterDbContext : DbContext
{
public TwitterDbContext() : base("Twitter")
{
}
public DbSet<Stream> Streams { get; set; }
public DbSet<StreamParameter> StreamParameters { get; set; }
public DbSet<Tweet> Tweets { get; set; }
}
public class Tweet
{
public Tweet()
{
}
[Key]
public long tweet_id { get; set; }
public string tweet { get; set; }
public long creator { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }
public string language { get; set; }
public DateTime created_at { get; set; }
public DateTime registered_at { get; set; }
public long? in_reply_to { get; set; }
public bool retweeted { get; set; }
}
我有一个其他类来存储Tweet表使用的所有字段的代码执行。对于这里的需要,让我们想象一下我手动创建它
private void Test_Button_Click(object sender, RoutedEventArgs e)
{
Twts twtReceived = new Twts();
twtReceived.tweet_id = 1;
twtReceived.tweet = "test";
twtReceived.creator = 1;
twtReceived.latitude = -1;
twtReceived.longitude = -1;
twtReceived.language = "a";
twtReceived.created_at = DateTime.Now;
twtReceived.registered_at = DateTime.Now;
twtReceived.in_reply_to = 1;
twtReceived.retweeted = true;
AddTweet(twtReceived);
}
现在这里是AddTweet方法
static public void AddTweet(Twts twtReceived)
{
try
{
// update the tweet data in the database
using (var TwitterDb = new TwitterDbContext())
{
Tweet twt = new Tweet()
{
tweet_id = twtReceived.tweet_id,
tweet = twtReceived.tweet,
creator = twtReceived.creator,
longitude = twtReceived.longitude,
latitude = twtReceived.latitude,
language = twtReceived.language,
created_at = twtReceived.created_at,
registered_at = twtReceived.registered_at,
in_reply_to = twtReceived.in_reply_to,
retweeted = twtReceived.retweeted
};
TwitterDb.Tweets.Add(twt);
TwitterDb.SaveChanges();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.InnerException.ToString());
}
}
我经常收到同样的错误消息:
无法将值NULL插入列'tweet_id',表中 'Twitter.dbo.Tweets';列不允许空值。 INSERT失败。
事情就是当我在TwitterDb.Tweets.Add(twt)之后窥探“TwitterDb.Tweets.Local”时;我正确地将tweet_id设置为1。
知道问题在哪里?
答案 0 :(得分:0)
尝试使用以下(而不仅仅是[Key])标记您的tweet_id字段,如果这是您想要自己提供值的主键列
[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
如果是自动增量,则删除此字段的显式分配,并将其标记为“#39; Identity&#39;相反:
[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]