A referential integrity constraint violation occurred. When Updating EF - c#

I can't seem to be able to update a model with foreignKey constraint getting this error :
Additional information: A referential integrity constraint violation
occurred: The property value(s) of 'Country.Id' on one end of a
relationship do not match the property value(s) of 'Setting.CountryId'
on the other end.
Setting Model
namespace Domain
{
public class Setting : BaseModel
{
public string Address { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Website { get; set; }
public string Slogan { get; set; }
public byte[] Logo { get; set; }
public string City { get; set; }
public string RegistrationNo { get; set; }
[ForeignKey("State")]
public int StateId { get; set; }
public State State { get; set; }
[ForeignKey("Country")]
public int CountryId { get; set; }
public Country Country { get; set; }
public string IsDefault { get; set; }
}
}
State Model
namespace Domain
{
public class State :BaseModel
{
public string Name { get; set; }
}
}
Country Model
namespace Domain
{
public class Country : BaseModel
{
public string Name { get; set; }
}
}
Repository to Get and Update Setting
public Setting GetSetting()
{
try
{
return _db.Settings.Include("Country").Include("State").First();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public Setting UpdateSetting(Setting setting)
{
try
{
_db.Settings.Attach(setting);
_db.Entry(setting).State = EntityState.Modified;
_db.SaveChanges();
return setting;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
Note I am Using WCF Proxy
Button Click Event
private void btnSave_Click(object sender, EventArgs e)
{
//MessageBox.Show(Convert.ToInt16(cmbState.EditValue).ToString());
//return;
if (dxValidationProvider1.Validate())
{
if (picLogo.Image == null)
{
XtraMessageBox.Show("Upload Logo");
}
else
{
var setting = proxy.GetSetting();
//MessageBox.Show(cmbState.EditValue.ToString()); return;
setting.HotelName = txtHotelName.Text;
setting.Address = txtAddress.Text;
setting.Email = txtEmail.Text;
setting.Phone = txtPhone.Text;
setting.Website = txtWebsite.Text;
setting.Slogan = txtSlogan.Text;
setting.City = txtCity.Text;
setting.CountryId = Convert.ToInt16(cmbCounty.EditValue);
setting.StateId = Convert.ToInt16(cmbState.EditValue));
setting.Logo = picLogo.Image.ToByteArray();
var s = proxy.UpdateSetting(setting);
MessageBox.Show(#"Updated");
}
}
else
{
MessageBox.Show("Please fill the required fields");
}
}

I just removed the Include statment from the GetSetting function and everything updated. This solved my problem
public Setting GetSetting()
{
try
{
return _db.Settings.First();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}

Related

Saving data in the database using Entity Framework

I am trying to save data in the database using Entity Framework and this code, but I keep getting this error:
System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at GDEProject.Pages.Profile.Update_Click(Object sender, EventArgs e) in
C:\Users\RATAU\Documents\Projects\GDEProject\GDEProject\GDEProject\Pages\Profile.aspx.cs:line 48
This is the code I am using:
public partial class Profile : System.Web.UI.Page
{
Entities2 db = new Entities2();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Update_Click(object sender, EventArgs e)
{
if (ModelState.IsValid)
{
try
{
PROFILE user = new PROFILE();
user.IdNumber = IdNumber.Text;
user.PersalNumber = ParselNumber.Text;
user.Title = Title.Text;
user.Initials = Initial.Text;
user.Name = FirstName.Text;
user.Surname = LastName.Text;
user.Age = Age.Text;
user.Race = Race.Text;
user.EmailAddress = Email.Text;
user.CellPhone = Phonenumber.Text;
user.TelephoneNumber = Telephone.Text;
user.Nationality = dropNationality.SelectedValue.ToString();
user.Gender = dropGender.SelectedValue.ToString();
user.Disability = Disability.SelectedValue.ToString();
user.DisabilityType = DisabilityType.Text;
db.PROFILEs.Add(user);
db.SaveChanges();
ErrorMessage.Text = "saved";
}
catch (Exception ee)
{
ErrorMessage.Text = ("error" + ee);
}
}
else
{
ErrorMessage.Text="modelstate failed";
}
}
the class of profile is as follows:
public partial class PROFILE
{
public string Nationality { get; set; }
public string IdNumber { get; set; }
public string PersalNumber { get; set; }
public string Title { get; set; }
public string Initials { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Age { get; set; }
public string Gender { get; set; }
public string Race { get; set; }
public string Language { get; set; }
public string EmailAddress { get; set; }
public string CellPhone { get; set; }
public string TelephoneNumber { get; set; }
public string Disability { get; set; }
public string DisabilityType { get; set; }
public string Message { get; set; }
}
}
Please assist

SQLite Xamarin/C# inserting data

I am developing an application. I have connected my project to SQLIte, now I am trying to add an advert, which I am failing to do.
my SQLInterface
public interface ISQLiteInterface
{
SQLiteConnection GetSQLiteConnection();
}
my Droid SQL
public class SQLiteDb : ISQLiteInterface
{
public SQLiteDb()
{
}
public SQLiteConnection GetSQLiteConnection()
{
var fileName = "Mydatabase.db";
var dbpath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(dbpath, fileName);
var connection = new SQLiteConnection(path);
return connection;
}
}
}
my model
public class AdLogEntry
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string SellerName { get; set; }
public string Name { get; set; }
public List<Picture> Pictures { get; set; }
public List<Video> Videos { get; set; }
public string Image { get; set; }
public string Video { get; set; }
public string Description { get; set; }
public string Price { get; set; }
public string LoadedDate { get; set; }
public string Location { get; set; }
public int Age { get; set; }
}
public class Picture
{
public string Id { get; set; }
public string Url { get; set; }
public byte[] Image { get; set; }
}
public class Video
{
public string Id { get; set; }
public string Url { get; set; }
public byte[] ImageVideo { get; set; }
}
}
this is my task
private async void NextStep_Clicked(object sender, EventArgs e)
{
await SaveAdLog();
}
private async Task SaveAdLog()
{
if (string.IsNullOrWhiteSpace(NameEntry.Text) || (string.IsNullOrWhiteSpace(PriceEntry.Text) || (string.IsNullOrWhiteSpace(LocationEntry.Text))))
{
await DisplayAlert("error", "fill all entries", "OK");
}
else {
var adLogEntry = new AdLogEntry
{
Location = LocationEntry.Text,
Price = PriceEntry.Text,
Name = NameEntry.Text,
};
var result = _adService.CreateAddLogEntry(adLogEntry); //ok
if (result == null)
{
await DisplayAlert("Gratulace", "", "OK");
App.Current.MainPage = new AppShell();
}
};
}
this is my advertservice
class AdService
{
private SQLiteConnection _conn;
public AdService()
{
_conn = DependencyService.Get<Helpers.ISQLiteInterface>().GetSQLiteConnection();
_conn.CreateTable<AdLogEntry>();
}
public string CreateAddLogEntry(AdLogEntry adLogEntry)
{
var detail = _conn.Table<AdLogEntry>();
var d1 = detail.Connection.Insert(adLogEntry);
return "Thank you";
}
}
}
Once I press the button nothing happens. When I try to debug it i get 'Object reference not set to an instance of an object.'
Edit.
This app is supposed to be something like LetItGo so all values should be able to repeat
I have ISQLite interface implemented.
According to your error message, I can not see where you instantiate a new instance of the AdService class.
So please try to add the following code before you call _adService.CreateAddLogEntry() method.
_adService = new AdService();
i think SQLite can't process this properties in your model
List< Picture > and
List< Video >
public List<Picture> Pictures { get; set; }
public List<Video> Videos { get; set; }
I suggest that you change the property to string and serialize the data before saving

C# ASP.Net - Error when trying to delete data from table

I have table Player and table Statistic and other tables that are not important in this question.
Table Player has PK Player_ID and it is FK in table Statistic. The relationship between these tables is one-to-many (one player can have more statistics).
Here is the code:
GenericRepository(I have created it to have unique class for CRUD methods)
public async Task<int> Delete<T>(Guid id) where T : class
{
try
{
T entity = await Get<T>(id);
Context.Set<T>().Remove(entity);
return await Context.SaveChangesAsync();
}
catch (Exception ex)
{
throw ex;
}
}
PlayerRepository(for managing operations on Player table)
public async Task<int> Delete(Guid id)
{
try
{
var player = await GenRepository.Get<Player>(id);
if (player == null)
{
return 404;
}
else
{
return await GenRepository.Delete(player);
}
}
catch (Exception ex)
{
throw ex;
}
}
PlayerService(connection between repository and controller in WebAPI)
public async Task<int> Delete(Guid id)
{
try
{
return await PlayerRepository.Delete(id);
}
catch (Exception ex)
{
throw ex;
}
}
PlayerController
[HttpDelete]
[Route("deleteplayer")]
public async Task<HttpResponseMessage> Delete(Guid id)
{
try
{
var Finder = Mapper.Map<PlayerView>(await PlayerService.Get(id));
if(Finder == null)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Player doesn't exist in database.");
}
var Response = await PlayerService.Delete(id);
var profile = "../../../app/pictures/FootballFanAppPictures/" + Finder.Club_ID.ToString().ToUpper() + "/profiles/" + id.ToString().ToUpper() + ".png";
var details = "../../../app/pictures/FootballFanAppPictures/" + Finder.Club_ID.ToString().ToUpper() + "/" + id.ToString().ToUpper() + ".png";
if (System.IO.File.Exists(profile))
{
System.IO.File.Delete(profile);
}
if (System.IO.File.Exists(details))
{
System.IO.File.Delete(details);
}
return Request.CreateResponse(HttpStatusCode.OK, Response);
}
catch(Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
Entity models:
-database models
public partial class Player
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Player()
{
this.Statistic = new HashSet<Statistic>();
}
public System.Guid Player_ID { get; set; }
public System.Guid Club_ID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public double Height { get; set; }
public int Weight { get; set; }
public System.DateTime BirthDate { get; set; }
public string Nationality { get; set; }
public string Position { get; set; }
public int Shirtnmbr { get; set; }
public virtual Club Club { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Statistic> Statistic { get; set; }
}
using System;
using System.Collections.Generic;
public partial class Statistic
{
public System.Guid Statistic_ID { get; set; }
public System.Guid Player_ID { get; set; }
public int Goals { get; set; }
public int Assists { get; set; }
public int FoulsFor { get; set; }
public int FoulsAgainst { get; set; }
public int ShotsTotal { get; set; }
public int ShotsGoal { get; set; }
public virtual Player Player { get; set; }
}
-domain models (used in repository)
public class PlayerDomain : IPlayerDomain
{
public Guid Player_ID { get; set; }
public Guid Club_ID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public double Height { get; set; }
public int Weight { get; set; }
public DateTime BirthDate { get; set; }
public string Nationality { get; set; }
public string Position { get; set; }
public int Shirtnmbr { get; set; }
public virtual ICollection<IStatisticDomain> Statistic { get; set; }
}
public class StatisticDomain: IStatisticDomain
{
public Guid Statistic_ID { get; set; }
public Guid Player_ID { get; set; }
public int Goals { get; set; }
public int Assists { get; set; }
public int FoulsFor { get; set; }
public int FoulsAgainst { get; set; }
public int ShotsTotal { get; set; }
public int ShotsGoal { get; set; }
}
-view models (used in controller)
public class PlayerView
{
public Guid Player_ID { get; set; }
public Guid Club_ID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public double Height { get; set; }
public int Weight { get; set; }
public DateTime BirthDate { get; set; }
public string Nationality { get; set; }
public string Position { get; set; }
public int Shirtnmbr { get; set; }
public virtual ICollection<StatisticView> Statistic { get; set; }
}
public class StatisticView
{
public Guid Statistic_ID { get; set; }
public Guid Player_ID { get; set; }
public int Goals { get; set; }
public int Assists { get; set; }
public int FoulsFor { get; set; }
public int FoulsAgainst { get; set; }
public int ShotsTotal { get; set; }
public int ShotsGoal { get; set; }
}
Every class is in a separate file. I use database first approach so i got .edmx file along with database models. Database is created in SQL Server Management Studio.
I can update Player but when I try to delete it i get this error:
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
I have searched various answers on google and stackoverflow but I couldn't find an answer that solves my problem
Before you call this line:
var Response = await PlayerService.Delete(id);
You are going to need to retrieve a list of your statistics that are assigned to the player you are trying to delete.
Then loop trough each of the statistics and delete those from your database first.
var stats = Finder.Statistic.ToList();
if(stats != null && stats.Any())
{
foreach(var stat in stats)
{
//retrieve your stat record here from the database
//check that the stat record is not null
//delete your stat record here
}
}
Then you should be able to delete your player record as there will no longer be references to it.
OR
You could just set ON DELETE CASCADE to true, but you need to be careful that you fully understand what all will be deleted on player deletion.
I don't see Statistic deletion on Player delete in your code.
Before you can delete a Player, you need to delete all Player related Statistics first. If there is any left, a player will fail on delete operation.
Set PrimaryKey and Foreignkey Relationship :according to #Bad Dub suggestion.

An unhandled exception of type 'System.Data.Entity...ModelValidationException' occurred in EntityFramework.dll

So I'm in trouble with this error:
An unhandled exception of type
'System.Data.Entity.ModelConfiguration.ModelValidationException'
occurred in EntityFramework.dll.
private void button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Are you sure?");
var db = new AndmebaasContext();
Console.WriteLine("vajtuasid comboboxi");
string name = "Peeter";
int number = 5081976;
long isikukood = 39502266016;
bool Kliendikaart = true;
//DateTime TulebJargi = new DateTime(02, 01, 2015);
// DateTime ToobTagasi = new DateTime(23, 01, 2015);
string lumelauad = "Flow 150";
string MaeSuusad = "Rossignol 170";
var kliendinimi = new Kliendid { KliendiNimi = name};
db.Kontakt.Add(kliendinimi);// ERROR Seems to be HERE!!!
db.SaveChanges();
var query = from b in db.Kontakt
orderby b.KliendiNimi
select b;
foreach (var item in query)
{
Console.WriteLine(item.KliendiNimi);
}
So this was a part of a main script in wpf and i wrote a comment where visual studio compiler shows error for me.
public class AndmebaasContext : DbContext
{
public DbSet<Kliendid> Kontakt { get; set; }
public DbSet<KliendiRendiAndmed> KliendiRendiAndmed { get; set; }
public DbSet<KliendiRenditudVarustus> KliendiRenditudVarustus { get; set; }
}
and last class what is used to make database and propably there is a error
public class Kliendid
{
public int KliendiID { get; set; }
public string KliendiNimi { get; set; }
public int KliendiNumber { get; set; }
public long KliendiIsikukood { get; set; }
public bool KliendiKliendikaart { get; set; }
public virtual List<KliendiRendiAndmed> Kliendirendiandmed { get; set; }
}
public class KliendiRendiAndmed
{
public int KliendiRendiAndmeteID { get; set; }
public DateTime TulebJärgi { get; set; }
public DateTime ToobTagasi { get; set; }
public virtual List<KliendiRenditudVarustus> Kliendirenditudvarustus {get; set;}
}
public class KliendiRenditudVarustus
{
public int KliendiRenditudVarustuseID { get; set; }
public string LumeLaud { get; set; }
public string LumeLauaSaapad { get; set; }
public string MaeSuusk { get; set; }
public string MaeSuusaSaapad { get; set; }
public string SuusaKepid { get; set; }
public virtual Kliendid Kliendid { get; set; }
}
Hope that somebody can help me out so cheers and happy new year! :)
This is almost certainly because you are attempting to insert a Kliendid with only a name specified and one of the other properties is marked as Required and cannot be null. Specifically in your case it's almost certainly the KliendiNumber or KliendiID as those are integers and can't be null, unless you were using Keys and identity columns to auto increment them.
You have a couple options. One, you could actually look at the exception and see which property and error it is by trapping the exception and looking at the validation errors property.
Catch (DbEntityValidationException ex)
{
foreach (var validationError in ex.EntityValidationErrors) {
foreach (var errorDetail in validationError.ValidationErrors)
{
Console.WriteLine("Property: {0} Error: {1}",
errorDetail.PropertyName, errorDetail.ErrorMessage);
}
}
}
You can also change the model to allow nullable integers on those 2 fields
public int? KliendiID { get; set; }
public int? KliendiNumber { get; set; }

Using linq to update a composite key field

In our SQL database we have a table with a composite key that includes fields we need to update from time to time. It's my understanding that, since we are using the Entity Framework, I need to remove the record from the database first then add the row back to the table.
Below is the simple method I created to handle an "update" since there are numerous methods that will be carrying this out. However, once the .SaveChanges() method is called after the .Remove I get the DbUpdateConcurrencyException:
Store update, insert, or delete statement affected an unexpected number of
rows (0). Entities may have been modified or deleted since entities were loaded.
Refresh ObjectStateManager entries.
Not sure what I'm doing wrong as I'm trying to remove the record, then perform the updates, then add the record back.
Here's the method that calls the remove/edit methods. When this method is called, the record hasn't been altered in any way shape or form yet.
private static void ProcessAllChanges(ZipCodeIndex information, ZipCodeTerritory zipToUpdate)
{
try
{
RemoveRecord(zipToUpdate);
if (!string.IsNullOrWhiteSpace(information.newTerritory)) zipToUpdate.IndDistrnId = information.newTerritory;
if (!string.IsNullOrWhiteSpace(information.newStateCode)) zipToUpdate.StateCode = information.newStateCode;
if (!string.IsNullOrWhiteSpace(information.newDescription)) zipToUpdate.DrmTerrDesc = information.newDescription;
if (!string.IsNullOrWhiteSpace(information.newChannelCode)) zipToUpdate.ChannelCode = information.newChannelCode;
if (zipToUpdate.EndDate == DateTime.MinValue) zipToUpdate.EndDate = DateTime.MaxValue;
EditRecord(zipToUpdate);
_updated++;
}
catch (DbEntityValidationException dbEx)
{
_msg += "Error during update; ";
EventLog.WriteEntry("Monet", "Error during ProcessAllChanges: " + zipToUpdate.ToString() + " |EX| " + dbEx.Message);
}
catch (Exception ex)
{
_msg += "Error during update; ";
EventLog.WriteEntry("Monet", "Error during ProcessAllChanges: " + zipToUpdate.ToString() + " |MESSAGE| " + ex.Message);
}
}
And here are the two helper methods that get called
public static void RemoveRecord(ZipCodeTerritory zipCode)
{
_db = new AgentResources();
_db.ZipCodeTerritory.Attach(zipCode);
_db.ZipCodeTerritory.Remove(zipCode);
_db.SaveChanges();
}
public static void EditRecord(ZipCodeTerritory zipCode)
{
_db = new AgentResources();
_db.ZipCodeTerritory.Add(zipCode);
_db.SaveChanges();
}
EDIT
Based on a couple comments below I attempted to create a separate instance of the context object, however i received the same error using this method:
public static void RemoveRecord(ZipCodeTerritory zipCode)
{
using (AgentResources deleteMe = new AgentResources())
{
deleteMe.ZipCodeTerritory.Attach(zipCode);
deleteMe.ZipCodeTerritory.Remove(zipCode);
deleteMe.SaveChanges();
}
}
Second Edit
Here is the upper most method which calls the ProcessAllChanges method I posted above.
public static string TerritoryOnly(ZipCodeIndex updateZip)
{
if (!string.IsNullOrWhiteSpace(updateZip.newEffectiveDate) || !string.IsNullOrWhiteSpace(updateZip.newEndDate))
{
return "Neither effective or end date can be present if updating Territory Code only; ";
}
RefreshProperties();
foreach (var zipCode in updateZip.displayForPaging.Where(x => x.Update))
{
ProcessAllChanges(updateZip, zipCode);
}
_msg += _updated + " record(s) updated; ";
return _msg;
}
Third Edit
Per request here is the full class definition of AgentResources, our DbContext object
namespace Monet.Models
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class AgentResources : DbContext
{
public AgentResources()
: base("name=AgentResources")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<AgentContEd> AgentContEd { get; set; }
public DbSet<ContEdCourse> ContEdCourse { get; set; }
public DbSet<Course> Course { get; set; }
public DbSet<CourseToProduct> CourseToProduct { get; set; }
public DbSet<Product> Product { get; set; }
public DbSet<ProcessControl> ProcessControl { get; set; }
public DbSet<AgentIdToTradingPartner> AgentIdToTradingPartner { get; set; }
public DbSet<TradingPartner> TradingPartner { get; set; }
public DbSet<Notes> Notes { get; set; }
public DbSet<CourseMaterials> CourseMaterials { get; set; }
public DbSet<TransactionLog> TransactionLog { get; set; }
public DbSet<Agent> Agent { get; set; }
public DbSet<AgentIdentification> AgentIdentification { get; set; }
public DbSet<BatchDashboard> BatchDashboard { get; set; }
public DbSet<BatchPrograms> BatchPrograms { get; set; }
public DbSet<FollowUpItems> FollowUpItems { get; set; }
public DbSet<sysdiagrams> sysdiagrams { get; set; }
public DbSet<AgentProductTraining> AgentProductTraining { get; set; }
public DbSet<Channel> Channel { get; set; }
public DbSet<RelationshipCodes> RelationshipCodes { get; set; }
public DbSet<DropDownValues> DropDownValues { get; set; }
public DbSet<QueueUpdates> QueueUpdates { get; set; }
public DbSet<MarketingLookup> MarketingLookup { get; set; }
public DbSet<TransmissionHistory> TransmissionHistory { get; set; }
public DbSet<AgentTransmission> AgentTransmission { get; set; }
public DbSet<ZipCodeTerritory> ZipCodeTerritory { get; set; }
}
}
Here is the ZipCodeTerritory class
public partial class ZipCodeTerritory
{
public string ChannelCode { get; set; } //Composite key field
public string DrmTerrDesc { get; set; }
public string IndDistrnId { get; set; }
public string StateCode { get; set; } //Composite key field
public string ZipCode { get; set; } //Composite key field
public System.DateTime? DisplayEndDate { get; set; }
public System.DateTime EndDate { get; set; } //Composite key field
public System.DateTime EffectiveDate { get; set; }
public string LastUpdateId { get; set; }
public Nullable<System.DateTime> LastUpdateDate { get; set; }
}
Try this :
public static void RemoveRecord(ZipCodeTerritory zipCode)
{
using(var _newdb = new AgentResources())
{
ZipCodeTerritory zipCodeRemove = new ZipCodeTerritory();
zipCodeRemove.channelCode = zipCode.channelCode;
zipCodeRemove.stateCode = zipCode.stateCode;
zipCodeRemove.zipCode= zipCode.zipCode;
zipCodeRemove.endDate = zipCode.endDate;
_newdb.ZipCodeTerritory.Attach(zipCodeRemove);
_newdb.ZipCodeTerritory.Remove(zipCodeRemove);
//((IObjectContextAdapter)_newdb).ObjectContext.Refresh(
// RefreshMode.ClientWins
//, zipCode);
_newdb.SaveChanges();
}
}

Categories