asp.net - Entity Framework : A referential integrity constraint violation occurred when I do EntityState.Modified -


i create website in asp.net mvc 4. it's been long have error : referential integrity constraint violation occurred. it's when tried update entry in db. when want buy product, need change user buy.

i have 2 1 many relationship.

edit user class :

public class user {     private string email, password, firstname, lastname;     private adress shippingadress, billingadress;     private bool isconnected;     private list<product> products;     //private list<auction> auctions;     private long idshippinga, idbillinga;      public user()     {         products = new list<product>();     }     /* public list<auction> auctions     {         { return auctions; }         set { auctions = value; }     }      public void addauction(auction auction)     {         if (auction != null)             auctions.add(auction);     }*/      public long idbillinga     {         { return idbillinga; }         set         {             if (value < 0)                 throw new argumentexception("the id of billing adress should not negative");             idbillinga = value;         }     }      public long idshippinga     {         { return idshippinga; }         set         {             if (value < 0)                 throw new argumentexception("the id of shipping adress should not negative");             idshippinga = value;         }     }      public bool isconnected     {         { return isconnected; }         set { isconnected = value; }     }      public virtual list<product> products     {         { return products; }         set         {             if (value == null)                 throw new argumentnullexception("the list of product should not null");             products = value;         }     }      public adress billingadress     {         { return billingadress; }         set         {             if (value == null)                 throw new argumentnullexception("the billing adress should not null");             billingadress = value;         }     }      public adress shippingadress     {         { return shippingadress; }         set         {             if (value == null)                 throw new argumentnullexception("the shipping adress should not null");             shippingadress = value;         }     }      public string password     {         { return password; }         set         {             if (string.isnullorwhitespace(value))                 throw new argumentexception("the password should not null or empty");             password = value;         }     }      public string email     {         { return email; }         set         {             if (string.isnullorwhitespace(value))                 throw new argumentexception("the email should not null or empty");             email = value;         }     }      public string lastname     {         { return lastname; }         set         {             if (string.isnullorwhitespace(value))                 throw new argumentexception("the lastname should not null or empty");             lastname = value;         }     }      public string firstname     {         { return firstname; }         set         {             if (string.isnullorwhitespace(value))                 throw new argumentexception("the fistname should not null or empty");             firstname = value;         }     } }     } 

edit product class :

public class product {     private long id, strategyid;     private user userwhosell;         private user userwhobuy;     private string userwhosellid, userwhobuyid, name, description, urlpicture, isbought;      public string isbought     {         { return isbought; }         set { isbought = value; }     }     private sellstrategy strategy;     private float price;     private string strategystring;     public product()     {         isbought = "f";     }      public float price     {         { return price; }         set          {             if (value < 0)                 throw new argumentexception("the price should not negative");             price = value;          }     }      public string strategystring     {         { return strategystring; }         set          {             if (string.isnullorwhitespace(value))                 throw new argumentexception("the strategy string should not null, empty or white space");             strategystring = value;          }     }      public long strategyid     {         { return strategyid; }         set          {             if (value < 0)                 throw new argumentexception("the strategy id should not negative");             strategyid = value;          }     }      public sellstrategy strategy     {         { return strategy; }         set          {             if (value == null)                 throw new argumentnullexception("the strategy should not null");             strategy = value;          }     }      public string sellerid     {         { return userwhosellid; }         set          {             if (string.isnullorwhitespace(value))                 throw new argumentexception("the user id should not null, empty or white space");             userwhosellid = value;          }     }      public string buyerid     {         { return userwhobuyid; }         set          {             userwhobuyid = value;          }     }      public string urlpicture     {         { return urlpicture; }         set          {             if (string.isnullorwhitespace(value))                 throw new argumentexception("the picture's url should not null, empty or white space");             urlpicture = value;          }     }      public long id     {         { return id; }         set          {             if (value < 0)                 throw new argumentexception("the id should not negative");             id = value;         }     }      public string description     {         { return description; }         set         {             if (string.isnullorwhitespace(value))                 throw new argumentexception("the description should not null, empty or white space");             description = value;         }     }      public string name     {         { return name; }         set         {             if (string.isnullorwhitespace(value))                 throw new argumentexception("the name should not null, empty or white space");             name = value;         }     }      public virtual user buyer     {         { return userwhobuy; }         set         {             userwhobuy = value;         }     }      public virtual user seller     {         { return userwhosell; }         set          {             if (value == null)                 throw new argumentnullexception("the user should not null");             userwhosell = value;          }     } } 

edit context :

public class context : dbcontext {     public context(string connstring)         : base(connstring) { }      public dbset<user> users { get; set; }     public dbset<adress> adress { get; set; }     public dbset<product> products { get; set; }      //public dbset<auction> auctions { get; set; }      public dbset<sellstrategy> strategies { get; set; }      protected override void onmodelcreating(dbmodelbuilder modelbuilder)     {         base.onmodelcreating(modelbuilder);         modelbuilder.entity<user>().haskey<string>(u => u.email);         modelbuilder.entity<adress>().haskey<long>(a => a.id);         modelbuilder.entity<product>().haskey<long>(p => p.id);         modelbuilder.entity<auction>().haskey<long>(au => au.id);          modelbuilder.entity<product>()      .hasrequired(p => p.seller)      .withmany(u => u.products)      .hasforeignkey(p => p.sellerid)      .willcascadeondelete(false);         // otherwise might "cascade causes cycles" error          modelbuilder.entity<product>()            .hasoptional(p => p.buyer)            .withmany() // no reverse navigation property            .hasforeignkey(p => p.buyerid)            .willcascadeondelete(false);         // modelbuilder.entity<auction>().hasmany<user>(au => au.users).withmany(u => u.auctions);        // modelbuilder.entity<auction>().hasrequired(au => au.product).withmany().willcascadeondelete(false);          modelbuilder.entity<user>().hasrequired(u => u.billingadress).withmany().hasforeignkey(u => u.idbillinga).willcascadeondelete(false);         modelbuilder.entity<user>().hasrequired(u => u.shippingadress).withmany().hasforeignkey(u => u.idshippinga).willcascadeondelete(false);         modelbuilder.entity<user>().ignore(u => u.isconnected);            modelbuilder.entity<product>().hasrequired<sellstrategy>(p => p.strategy).withmany().willcascadeondelete(false);         modelbuilder.entity<product>().ignore(p => p.strategystring);         modelbuilder.entity<product>().ignore(p => p.price);          modelbuilder.entity<sellstrategy>().property(s => s.id).hasdatabasegeneratedoption(databasegeneratedoption.none);         modelbuilder.entity<auctionselling>().haskey<long>(a => a.id);         modelbuilder.entity<auctionselling>().map(m =>         {             m.mapinheritedproperties();             m.totable("auctionselling");         });         modelbuilder.entity<directselling>().haskey<long>(d => d.id);         modelbuilder.entity<directselling>().map(m =>         {             m.mapinheritedproperties();             m.totable("directselling");         });         modelbuilder.entity<sellstrategy>().property(s => s.solddate).isoptional();     } } 

edit , when try update product :

public void updateproduct(product product)     {         using(context context = new context(connectionstring))         {             try             {                 product p = getbyid(product.id);                 //context.products.attach(p);                 p.buyerid = product.buyerid;                 p.buyer = product.buyer;                 p.isbought = "t";                  context.entry(p).state = entitystate.modified;                 context.savechanges();             }             catch (exception ex)             {             }         }     } 

this line

context.entry(p).state = entitystate.modified;

that provoke error.

this full error

a referential integrity constraint violation occurred: property value(s) of 'user.email' on 1 end of relationship not match property value(s) of 'product.buyerid' on other end.

when context.savechanges, nothing occurs... don't know do... want cry ^^... thank lot in advance !

this caused setting reference navigation properties in constructor. specifically:

userwhosell = new user(); userwhobuy = new user(); 

this means product starts out having 2 dummy user objects have replace them become meaningful. otherwise ef may try save these dummy objects. i'm pretty sure by...

context.entry(p).entity.buyer = product.buyer; 

...you set such empty user object, has key value no email, not key value product.buyerid apparently set before.

i'd say: remove of these initializations in entities' constructors. initializing collections makes sense. setting default values (but not primary key value), reference navigation properties never. see also: ef codefirst : should initialize navigation properties?

side note: neither use property setters validations. that's data annotations for. these exceptions may interfere ef when trying materialize entities database.


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -