我试图使用Entity Framework保存状态消息,但问题是每次我尝试从数据库中已存在的用户保存推文时,我都会遇到异常!
{"A duplicate value cannot be inserted into a unique index. [ Table name = users,Constraint name = PK_dbo.users ]"}
我完全理解为什么我会收到此错误,但不知道如何防止它!
要保存状态消息,请执行以下操作
版本1:
db.status.Add(status);
db.SaveChanges();
每条状态消息都包含完整的用户信息作为子实体。我使用这段代码的Model(status.cs& user.cs):https://github.com/swhitley/TwitterStreamClient
使用此问题的信息:Save detached entity in Entity Framework 6 我提出了这个想法:
版本2:
user usr = db.user.Where<user>(u => u.id == status.user.id).SingleOrDefault();
if (usr == null)
db.user.Add(status.user);
else
{
db.user.Attach(status.user);
db.Entry(status.user).State = EntityState.Modified;
}
db.status.Add(status);
db.SaveChanges();
但这只会导致下一条错误消息:
附加类型&#39; TwitterStreamClient.user&#39;的实体失败是因为 另一个相同类型的实体已经拥有相同的主键 值。使用&#39;附加&#39;方法或设置 一个实体的状态为“未变”&#39;或者&#39;修改&#39;如果有任何实体 图表具有冲突的键值。这可能是因为某些实体 是新的,尚未收到数据库生成的键值。在 这种情况使用&#39;添加&#39;方法或“添加”#39;实体状态跟踪 图表然后将非新实体的状态设置为“未更改”。要么 &#39;变形&#39;酌情。
这里要求的是我的状态和用户类:
user.cs:
using System;
using System.Globalization;
using System.Runtime.Serialization;
using System.ComponentModel.DataAnnotations;
namespace TwitterStreamClient
{
[DataContract]
public class user
{
//<user>
//<id>1401881</id>
// <name>Doug Williams</name>
// <screen_name>dougw</screen_name>
// <location>San Francisco, CA</location>
// <description>Twitter API Support. Internet, greed, users, dougw and opportunities are my passions.</description>
// <profile_image_url>http://s3.amazonaws.com/twitter_production/profile_images/59648642/avatar_normal.png</profile_image_url>
// <url>http://www.igudo.com</url>
// <lang>en</lang>
// <protected>false</protected>
// <followers_count>1027</followers_count>
// <profile_background_color>9ae4e8</profile_background_color>
// <profile_text_color>000000</profile_text_color>
// <profile_link_color>0000ff</profile_link_color>
// <profile_sidebar_fill_color>e0ff92</profile_sidebar_fill_color>
// <profile_sidebar_border_color>87bc44</profile_sidebar_border_color>
// <friends_count>293</friends_count>
// <created_at>Sun Mar 18 06:42:26 +0000 2007</created_at>
// <favourites_count>0</favourites_count>
// <utc_offset>-18000</utc_offset>
// <time_zone>Eastern Time (US & Canada)</time_zone>
// <profile_background_image_url>http://s3.amazonaws.com/twitter_production/profile_background_images/2752608/twitter_bg_grass.jpg</profile_background_image_url>
// <profile_background_tile>false</profile_background_tile>
// <statuses_count>3390</statuses_count>
// <notifications>false</notifications>
// <following>false</following>
// <verified>true</verified>
// <contributors_enabled>false</verified>
//</user>
[DataMember]
[Key]
public string id { get; set; }
[DataMember]
public string name { get; set; }
[DataMember]
public string screen_name { get; set; }
[DataMember]
public string location { get; set; }
[DataMember]
public string description { get; set; }
[DataMember]
public string profile_image_url { get; set; }
[DataMember]
public string url { get; set; }
[DataMember]
public string lang { get; set; }
[DataMember]
public string @protected { get; set; }
[DataMember]
public string followers_count { get; set; }
[DataMember]
public string profile_background_color { get; set; }
[DataMember]
public string profile_text_color { get; set; }
[DataMember]
public string profile_link_color { get; set; }
[DataMember]
public string profile_sidebar_fill_color { get; set; }
[DataMember]
public string profile_sidebar_border_color { get; set; }
[DataMember]
public string friends_count { get; set; }
//save date only as string for now as DateTimeOffset is not supported
//public DateTimeOffset created_at_dt { get; set; }
[DataMember]
public string created_at
{
get ; //{ return created_at_dt.ToString("ddd MMM dd HH:mm:ss zzz yyyy"); }
set; //{ created_at_dt = DateTimeOffset.ParseExact(value, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture); }
}
[DataMember]
public string favourites_count { get; set; }
[DataMember]
public string utc_offset { get; set; }
[DataMember]
public string time_zone { get; set; }
[DataMember]
public string profile_background_image_url { get; set; }
[DataMember]
public string profile_background_tile { get; set; }
[DataMember]
public string statuses_count { get; set; }
[DataMember]
public string notifications { get; set; }
[DataMember]
public string following { get; set; }
[DataMember]
public string verified { get; set; }
[DataMember]
public string contributors_enabled { get; set; }
}
}
status.cs
using System;
using System.Runtime.Serialization;
using System.Globalization;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace TwitterStreamClient
{
//<status>
//<created_at>Tue Apr 07 22:52:51 +0000 2009</created_at>
//<id>1472669360</id>
//<text>At least I can get your humor through tweets. RT @abdur: I don't mean this in a bad way, but genetically speaking your a cul-de-sac.</text>
//<source><a href="http://www.tweetdeck.com/">TweetDeck</a></source>
//<truncated>false</truncated>
//<in_reply_to_status_id></in_reply_to_status_id>
//<in_reply_to_user_id></in_reply_to_user_id>
//<favorited>false</favorited>
//<in_reply_to_screen_name></in_reply_to_screen_name>
//<geo/>
//<contributors/>
//</status>
[DataContract]
public class status
{
[DataMember]
[Key]
public string id { get; set; }
//save date only as string for now as DateTimeOffset is not supported
//public DateTimeOffset created_at_dt { get; set; }
[DataMember]
public string created_at
{
get; //{ return created_at_dt.ToString("ddd MMM dd HH:mm:ss zzz yyyy"); }
set; //{ created_at_dt = DateTimeOffset.ParseExact(value, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture); }
}
[DataMember]
public string text { get; set; }
[DataMember]
public string source { get; set; }
[DataMember]
public string truncated { get; set; }
[DataMember]
public string in_reply_to_status_id { get; set; }
[DataMember]
public string in_reply_to_user_id { get; set; }
[DataMember]
public string favorited { get; set; }
[DataMember]
public string in_reply_to_screen_name { get; set; }
[DataMember]
public user user { get; set; }
[DataMember]
public geo geo { get; set; }
[DataMember]
public string contributors { get; set; }
}
[DataContract]
public class geo
{
[Key]
public int geoId { get; set; }
[DataMember]
public string type { get; set; }
[DataMember]
public string[] coordinates { get; set; }
}
}
DataStore.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
namespace TwitterStreamClient
{
class DataStore
{
static private TweetContext Db = null;
private static TweetContext getContext() {
if(Db == null)
{
Db = new TweetContext();
}
return Db;
}
public static bool Add(status status)
{
TweetContext db = getContext();
{
db.status.Add(status);
db.SaveChanges();
return true;
}
}
}
}
TweetContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
namespace TwitterStreamClient
{
class TweetContext : DbContext
{
public DbSet<status> status { get; set; }
public DbSet<user> user { get; set; }
static TweetContext()
{
// Database initialize
Database.SetInitializer<TweetContext>(new DbInitializer());
using (TweetContext db = new TweetContext())
db.Database.Initialize(false);
}
class DbInitializer : DropCreateDatabaseAlways<TweetContext>
{
}
}
}
答案 0 :(得分:0)
我在插入时遇到同样的问题然后我得到错误我重新初始化dbcontext 我的问题解决了我不明白,但它对我来说很好
just reinitialize your dbcontext and check ....
答案 1 :(得分:0)
我找到了解决方案!
在上面的第2版中,我只需要将SingleOrDefault()
更改为Any<user>()
!
if(!db.user.Where<user>(u => u.id == status.user.id).Any<user>())
db.user.Add(status.user);
else
{
//db.user.Attach(status.user);
db.Entry(status.user).State = EntityState.Modified;
}
db.status.Add(status);
db.SaveChanges();
我认为使用SingleOrDefault()
的用户跟踪具有此ID的用户的问题因此Attach()
会抛出异常,因为它已经跟踪具有此ID的用户。但是当我使用Any<user>()
时,它只是用这个键来检查用户是否存在而且它不跟踪它!因此,可以附加用户。