SqlException: Cannot insert explicit value for identity column in table - c#

At first I'm sorry for using my native language in Code, but it's my University project and our project Leader ordered us to write like this.
I'm working on Database project using Entity Framework and C#.
In short, I've created class named "Osoba" and "Klient" class which inherits from "Osoba".
Problem is that when I'm trying to add new "Klient" to database I'm still getting error as following:
System.Data.Entity.Infrastructure.DbUpdateException: „An error occurred while updating the entries. See the inner exception for details.”
SqlException: Cannot insert explicit value for identity column in table 'Klient' when IDENTITY_INSERT is set to OFF.
I've researched similar problems in web, but all of them were appearing because of "hard-coding" ID while adding new object to table.. and I'm actually not doing this.
Here is Osoba class:
[Table("Osoba")]
public class Osoba
{
public int ID { get; set; }
public string Imie { get; set; }
public string Nazwisko { get; set; }
public string Telefon { get; set; }
public string Adres { get; set; }
public string Mail { get; set; }
public int IloscTransakcji { get; set; }
public string Typ { get; set; }
public override string ToString()
{
return "Imie: " + Imie + "\t Nazwisko: " + Nazwisko + "\t Adres: " + Adres;
}
}
Klient class:
[Table("Klient")]
public class Klient: Osoba
{
public int ID { get; set; }
public string Pracownik { get; set; }
public int Sprzedane { get; set; }
public int Kupione { get; set; }
public string Preferencje { get; set; }
public override string ToString()
{
return "Obslugujacy pracownik: " + Pracownik + "\t Sprzedane: " + Sprzedane.ToString() + "\t Kupione: " + Kupione.ToString();
}
}
My Database Context:
public class BazyDanychContext : DbContext
{
public BazyDanychContext() : base("ProjektBD8")
{
}
public DbSet<Osoba> Osoba { get; set; }
public DbSet<Klient> Klient { get; set; }
public DbSet<Pracownik> Pracownik { get; set; }
public DbSet<Nieruchomosc> Nieruchomosc { get; set; }
public DbSet<Biuro> Biuro { get; set; }
public DbSet<Dom> Dom { get; set; }
public DbSet<Grunt> Grunt { get; set; }
public DbSet<Hala> Hala { get; set; }
public DbSet<Mieszkanie> Mieszkanie { get; set; }
public DbSet<Spotkanie> Spotkanie { get; set; }
public DbSet<Umowa> Umowa { get; set; }
}
And finally here is how I'm adding new Klient to database:
private void KlientAdd_Click(object sender, RoutedEventArgs e)
{
using (var ctx = new BazyDanychContext())
{
Klient tmp = new Klient { Imie = KlientImie.Text, Nazwisko = KlientNazwisko.Text, Telefon = KlientTelefon.Text, Adres = KlientAdres.Text, Mail = KlientMail.Text, IloscTransakcji = Int32.Parse(KlientIloscTransakcji.Text), Typ = "Klient" , Pracownik = KlientPracownik.Text, Sprzedane = Int32.Parse(KlientSprzedane.Text), Kupione = Int32.Parse(KlientKupione.Text), Preferencje = KlientPreferencje.Text };
ctx.Osoba.Add(tmp);
ctx.SaveChanges();
}
InitTabs();
}

So, final solution for me was removing all migrations in my project. After dropping my Database, removing all migrations and then recreate Database without any migrations in my project it finally worked. Thank you for all your suggestions.

Related

I want to pass dynamically the <T> parameter to my function for read a data base

I have 2 or more class:
public class AllParam
{
public int Id { get; set; }
public string Data { get; set; }
public string Allarme { get; set; }
}
public class UtentiParam
{
public int Id { get; set; }
public string Utente { get; set; }
public string Psw { get; set; }
public string Livello { get; set; }
}
and I want to read data from my data base with this code:
var list = new List<AllParam>();
using (var db_ = new LiteDatabase(#"C:\HmiImpBroda\DataBase\" + TableToProcess + ".db"))
{
var col = db_.GetCollection<AllParam>(TableToProcess);
foreach (AllParam _id in col.FindAll())
{
list.Add(_id);
}
}
Exist a way to set set AllParam or CurveParam in my function from a string? in this way I can use the same code for each type of class without write other code.
Thanks.

"Cannot insert the value NULL into column" despite value not being NULL

I'm using Entity Framework to populate a an SQL database table. My object 'WebcpdActivity' has a property 'OwnerIdDsc' that is an int. This gets populated (along with all the other properties) with a value shortly before being saved to the database:
WebcpdActivity.OwnerIdDsc = 0;
webContext.CPDActivities.Add(WebcpdActivity);
webContext.SaveChanges();
At the point of SaveChanges I get an error:
Cannot insert the value NULL into column 'OwnerIdDsc', table 'CPDActivityRecord.dbo.CPDActivity'; column does not allow nulls. INSERT fails. The statement has been terminated.
When I step through the code at the point of SaveChanges the WebcpdActivity.OwnerIdDsc property is indeed '0' and not 'NULL'.
EDIT 1*: (edited again to add correct version)
'CPDActivity' class which 'WebcpdActivity' is an instance of
public partial class CPDActivity
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public CPDActivity()
{
this.CPDActivityExtendeds = new HashSet<CPDActivityExtended>();
}
public string ModifiedByName { get; set; }
public string ModifiedByYomiName { get; set; }
public string sb_cqmoduleidName { get; set; }
public string sb_eventdateidName { get; set; }
public string sb_MemberContactIdYomiName { get; set; }
public string sb_MemberContactIdName { get; set; }
public string CreatedOnBehalfByName { get; set; }
public string CreatedOnBehalfByYomiName { get; set; }
public string ModifiedOnBehalfByName { get; set; }
public string ModifiedOnBehalfByYomiName { get; set; }
public string CreatedByName { get; set; }
public string CreatedByYomiName { get; set; }
public System.Guid OwnerId { get; set; }
public string OwnerIdName { get; set; }
public string OwnerIdYomiName { get; set; }
public int OwnerIdDsc { get; set; }
public Nullable<int> OwnerIdType { get; set; }
public Nullable<System.Guid> OwningUser { get; set; }
public Nullable<System.Guid> OwningTeam { get; set; }
public System.Guid sb_cpdactivityId { get; set; }
public Nullable<System.DateTime> CreatedOn { get; set; }
public Nullable<System.Guid> CreatedBy { get; set; }
public Nullable<System.DateTime> ModifiedOn { get; set; }
public Nullable<System.Guid> ModifiedBy { get; set; }
public Nullable<System.Guid> CreatedOnBehalfBy { get; set; }
public Nullable<System.Guid> ModifiedOnBehalfBy { get; set; }
public Nullable<System.Guid> OwningBusinessUnit { get; set; }
public int statecode { get; set; }
public Nullable<int> statuscode { get; set; }
public byte[] VersionNumber { get; set; }
public Nullable<int> ImportSequenceNumber { get; set; }
public Nullable<System.DateTime> OverriddenCreatedOn { get; set; }
public Nullable<int> TimeZoneRuleVersionNumber { get; set; }
public Nullable<int> UTCConversionTimeZoneCode { get; set; }
public string sb_name { get; set; }
public Nullable<System.DateTime> sb_ActivityDate { get; set; }
public Nullable<bool> sb_confirmedbysupervisor { get; set; }
public Nullable<decimal> sb_CPDHours { get; set; }
public Nullable<decimal> sb_CPDPoints { get; set; }
public string sb_FutureDevelopment { get; set; }
public Nullable<System.DateTime> sb_FutureDevelopmentTargetDate { get; set; }
public string sb_ReflectedOutcome { get; set; }
public Nullable<int> sb_StructuredCPD { get; set; }
public Nullable<int> sb_type { get; set; }
public Nullable<int> sb_UnstructuredCPD { get; set; }
public Nullable<System.Guid> sb_MemberContactId { get; set; }
public Nullable<System.Guid> sb_cqmoduleid { get; set; }
public Nullable<System.Guid> sb_eventdateid { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<CPDActivityExtended> CPDActivityExtendeds { get; set; }
public static explicit operator CPDActivity(sb_cpdactivity v)
{
CPDActivity sb_cpda = new CPDActivity();
sb_cpda.ModifiedByName = v.ModifiedByName;
sb_cpda.ModifiedByYomiName = v.ModifiedByYomiName;
sb_cpda.sb_cqmoduleidName = v.sb_cqmoduleidName;
sb_cpda.sb_eventdateidName = v.sb_eventdateidName;
sb_cpda.sb_MemberContactIdYomiName = v.sb_MemberContactIdYomiName;
sb_cpda.sb_MemberContactIdName = v.sb_MemberContactIdName;
sb_cpda.CreatedOnBehalfByName = v.CreatedOnBehalfByName;
sb_cpda.CreatedOnBehalfByYomiName = v.CreatedOnBehalfByYomiName;
sb_cpda.ModifiedOnBehalfByName = v.ModifiedOnBehalfByName;
sb_cpda.ModifiedOnBehalfByYomiName = v.ModifiedOnBehalfByYomiName;
sb_cpda.CreatedByName = v.CreatedByName;
sb_cpda.CreatedByYomiName = v.CreatedByYomiName;
sb_cpda.OwnerId = v.OwnerId;
sb_cpda.OwnerIdName = v.OwnerIdName;
sb_cpda.OwnerIdYomiName = v.OwnerIdYomiName;
sb_cpda.OwnerIdDsc = v.OwnerIdDsc;
sb_cpda.OwnerIdType = v.OwnerIdType;
sb_cpda.OwningUser = v.OwningUser;
sb_cpda.OwningTeam = v.OwningTeam;
sb_cpda.sb_cpdactivityId = v.sb_cpdactivityId;
sb_cpda.CreatedOn = v.CreatedOn;
sb_cpda.CreatedBy = v.CreatedBy;
sb_cpda.ModifiedOn = v.ModifiedOn;
sb_cpda.ModifiedBy = v.ModifiedBy;
sb_cpda.CreatedOnBehalfBy = v.CreatedOnBehalfBy;
sb_cpda.ModifiedOnBehalfBy = v.ModifiedOnBehalfBy;
sb_cpda.OwningBusinessUnit = v.OwningBusinessUnit;
sb_cpda.statecode = v.statecode;
sb_cpda.statuscode = v.statuscode;
sb_cpda.VersionNumber = v.VersionNumber;
sb_cpda.ImportSequenceNumber = v.ImportSequenceNumber;
sb_cpda.CreatedOn = v.CreatedOn;
sb_cpda.TimeZoneRuleVersionNumber = v.TimeZoneRuleVersionNumber;
sb_cpda.UTCConversionTimeZoneCode = v.UTCConversionTimeZoneCode;
sb_cpda.sb_name = v.sb_name;
sb_cpda.sb_ActivityDate = v.sb_ActivityDate;
sb_cpda.sb_confirmedbysupervisor = v.sb_confirmedbysupervisor;
sb_cpda.sb_CPDHours = v.sb_CPDHours;
sb_cpda.sb_CPDPoints = v.sb_CPDPoints;
sb_cpda.sb_FutureDevelopment = v.sb_FutureDevelopment;
sb_cpda.sb_FutureDevelopmentTargetDate = v.sb_FutureDevelopmentTargetDate;
sb_cpda.sb_ReflectedOutcome = v.sb_ReflectedOutcome;
sb_cpda.sb_StructuredCPD = v.sb_StructuredCPD;
sb_cpda.sb_type = v.sb_type;
sb_cpda.sb_UnstructuredCPD = v.sb_UnstructuredCPD;
sb_cpda.sb_MemberContactId = v.sb_MemberContactId;
sb_cpda.sb_cqmoduleid = v.sb_cqmoduleid;
sb_cpda.sb_eventdateid = v.sb_eventdateid;
return sb_cpda;
}
}
EDIT 2
added whole of Using block
using (CPDWebContext webContext = new CPDWebContext())
{
Guid activityId = Guid.NewGuid();
sb_cpdactivity blankSb_cpdactivity = new sb_cpdactivity();
blankSb_cpdactivity = getCPDData.populateActivtyMetaData(blankSb_cpdactivity);
CPDActivity WebcpdActivity = new CPDActivity();
WebcpdActivity = (CPDActivity)blankSb_cpdactivity;
WebcpdActivity.sb_cpdactivityId = activityId;
WebcpdActivity.CreatedOn = DateTime.Now;
WebcpdActivity.ModifiedOn = DateTime.Now;
WebcpdActivity.statecode = 0;
WebcpdActivity.statuscode = 1;
WebcpdActivity.sb_MemberContactId = bsavaMember.MemberID;
decimal minutes = decimal.Parse(ddl_minutes.SelectedValue);
WebcpdActivity.sb_CPDHours = decimal.Parse(tb_hours.Text) + minutes;
WebcpdActivity.sb_name = tb_title.Text;
WebcpdActivity.sb_ActivityDate = Convert.ToDateTime(DateTime.ParseExact(tb_date.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture));
lbl_notification.Text = bsavaMember.UserName + ",\r\n" + bsavaMember.MemberNumber + ",\r\n" + bsavaMember.MemberID + ",\r\n" + WebcpdActivity.sb_ActivityDate.ToString();
CPDActivityExtended cpdActivityExtended = new CPDActivityExtended();
cpdActivityExtended.SubjectArea = tb_area.Text;
cpdActivityExtended.Notes = tb_notes.Text;
cpdActivityExtended.Location = tb_location.Text;
cpdActivityExtended.Username = bsavaMember.UserName;
cpdActivityExtended.MemberNumber = bsavaMember.MemberNumber;
cpdActivityExtended.ContactId = bsavaMember.MemberID;
cpdActivityExtended.CPDActivityId = activityId;
cpdActivityExtended.id = Guid.NewGuid();
cpdActivityExtended.ActiveRecord = 1;
// testing
int test = WebcpdActivity.OwnerIdDsc;
WebcpdActivity.OwnerIdDsc = 1;
//
webContext.CPDActivities.Add(WebcpdActivity); // error triggered here
webContext.CPDActivityExtendeds.Add(cpdActivityExtended);
try
{
webContext.SaveChanges();
}
catch (Exception exc)
{
string error = exc.Message.ToString();
}
}
EDIT 3
I tried to keep the code to the areas I though relevant but it seems this issue may be a little more involved than originally thought. Basically; we have a Microsoft CRM installation that has a table we needed to replicate and only update the replicated table and extend with a further table. This table was replicated without any key constraints but with the data types and data constraints. So basically Table A (sb_cpdactivity) in Database A has been replicated as Table B (CPDActivity) in Database B and I have added Table C (CPDActivityExtended) to Database B.
The idea being we read from the original but NOT save to it. So when we save or create a new record we only do it to the NEW table (Table B,C Database B) Hence there is a way of converting between the original and the duplicate, if needs be).
Table B and C are standalone tables in their own database. Table C has a foreign key that is the primary key of Table B. The webContext only connects to this one database.
Hope this makes sense.
Okay, this took a while and it turns out this error was caused by the edmx file not actually having a mapping to the column that was referenced in the error. So when entity framework passed the object over to the database, that column (and several others) were not included and the database was unable to add a row where a non-nullable column was expecting a value.
I updated the edmx file so that ALL of the columns mapped correctly and everything is now fine.
I think you can't insert a NULL value because you did not declare your int? OwnerIdDsc variable as being NULLABLE.
Go back to the class properties and see exactly how you declared it.

No such table sqlite when execute query on xamarin forms pcl

I have a problem with the reading of the tables on the SQLite database.
my OBJ_User class:
namespace Fimap.Models
{
public class OBJ_User
{
public int DLR_Id { get; set; }
public string DLR_Username { get; set; }
public string DLR_Password_Hash { get; set; }
public object DLR_Nome { get; set; }
public string DLR_Cognome { get; set; }
public int DLR_Tipo { get; set; }
public string DLR_Azienda { get; set; }
public object DLR_Telefono { get; set; }
public object DLR_Email { get; set; }
public int DLR_Abilitato { get; set; }
public object DLR_Time_Zone { get; set; }
public object DLR_Country { get; set; }
public string DLR_Culture { get; set; }
public object DLR_Email1 { get; set; }
public object DLR_MCC_Modello_Alias { get; set; }
public object DLR_Anagrafica { get; set; }
public object DLR_Firma { get; set; }
public bool IsFIMAP { get; set; }
public bool IsSTANDARD { get; set; }
public bool IsDealerOrFimap { get; set; } //true dealer - false user
public object DLR_Tipo_Esteso { get; set; }
public object DLR_Abilitato_Esteso { get; set; }
}
}
my interface in pcl project:
public interface IDatabaseConnection
{
SQLite.SQLiteConnection DbConnection();
}
Android
[assembly: Xamarin.Forms.Dependency(typeof(DatabaseConnection_Android))]
namespace Fimap.Droid
{
public class DatabaseConnection_Android : IDatabaseConnection
{
public SQLiteConnection DbConnection()
{
var dbName = "FimapDB.db3";
var path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), dbName);
return new SQLiteConnection(path);
}
}
}
iOS
[assembly: Xamarin.Forms.Dependency(typeof(DatabaseConnection_iOS))]
namespace App.iOS
{
public class DatabaseConnection_iOS : IDatabaseConnection
{
public SQLiteConnection DbConnection()
{
var dbName = "FimapDB.db3";
string personalFolder = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string libraryFolder = Path.Combine(personalFolder);
var path = Path.Combine(libraryFolder, dbName);
return new SQLiteConnection(path);
}
}
}
pcl connection (database is right connect):
database = DependencyService.Get<IDatabaseConnection>().DbConnection();
query:
var test = database.Query<OBJ_User>("SELECT * FROM OBJ_User");
when i launch the query i have this error:
SQLite.SQLiteException: no such table: OBJ_User
OBJ_User is in the dabatase with one record.
Why the connection don't mapping the table ?
database variable is right connect to database sqlite, i don't understand because database don't get mapping from sqlite file.
Solution ?
if you want other info write me in the comment, i will answer
The SQLite library doesn't know how to map the properties of type object to a sqlite column. The SQLite library supports the following column types by default: string, int, double, byte[], DateTime.

WPF, C# - group by object property

Is there a posibility to group by an object property in wpf?
For exmaple:
public class Ausgabe
{
public int Id { get; set; }
public Mitarbeiter Mitarbeiter { get; set; }
public Ausgabestatus Status { get; set; }
public Bestellung Bestellung { get; set; }
}
public class Mitarbeiter
{
public int Id { get; set; }
public String Vorname { get; set; }
public String Nachname { get; set; }
public String FullName
{
get { return Nachname + " " + Vorname; }
}
}
My datagrid's ItemsSource contains a List<Ausgabe> which i want to group by Mitarbeiter.FullName
CollectionView cv = (CollectionView)CollectionViewSource.GetDefaultView(dgErfasst.ItemsSource);
cv.GroupDescriptions.Clear();
PropertyGroupDescription pgd = new PropertyGroupDescription("Mitarbeiter.Vorname");
cv.GroupDescriptions.Add(pgd);
This does not seem to work. Is there a way to achieve this kind of grouping?
You can move FullName to parent class like
public class Ausgabe
{
public int Id { get; set; }
public Mitarbeiter Mitarbeiter { get; set; }
public Ausgabestatus Status { get; set; }
public Bestellung Bestellung { get; set; }
public String FullName
{
get { return Mitarbeiter.Nachname + " " + Mitarbeiter.Vorname; }
}
}
and then group
PropertyGroupDescription pgd = new PropertyGroupDescription("FullName");

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