NPGSQL relation "Blog" does not exist - entity-framework-core

I'm trying to set up entity framework core for a project and i'm working through the entity framework core guide on the NPGSQL site: https://www.npgsql.org/efcore/index.html
and i'm getting the following error:
Microsoft.EntityFrameworkCore.DbUpdateException
HResult=0x80131500
Message=An error occurred while saving the entity changes. See the inner exception for details.
Source=Microsoft.EntityFrameworkCore.Relational
StackTrace:
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IList`1 entries)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IList`1 entriesToSave)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(StateManager stateManager, Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<>c.<SaveChanges>b__104_0(DbContext _, ValueTuple`2 t)
at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
at Program.Main(String[] args) in C:\Users\brandp3.DTINET\source\repos\EF-ModelFirst\EF-ModelFirst\Program.cs:line 15
This exception was originally thrown at this call stack:
[External Code]
Inner Exception 1:
PostgresException: 42P01: relation "Blog" does not exist
POSITION: 13
here's the code:
static void Main(string[] args)
{
using (var db = new BloggingContext())
{
// Create and save a new Blog
Console.Write("Enter a name for a new Blog: ");
var name = Console.ReadLine();
var blog = new Blog { Name = name };
db.Blogs.Add(blog); // error thrown here
db.SaveChanges();
// Display all Blogs from the database
var query = from b in db.Blogs
orderby b.Name
select b;
Console.WriteLine("All blogs in the database:");
foreach (var item in query)
{
Console.WriteLine(item.Name);
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
The model:
public class Blog
{
public int ID { get; set; }
public string Name { get; set; }
public virtual List<Post> Posts { get; set; }
}
public class Post
{
public int ID { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
}
and the dbcontext setup
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql("Host=localhost;Database=postgres;Username=postgres;Password=mysecretpassword");
}
}
From what I understand the tables and relations should be created when I first run the program. At least the guide doesn't indicate that I need to push the schema to the database

From what I understand the tables and relations should be created when I first run the program.
EF Core doesn't automatically create the database schema for you - if you read this somewhere, can you please point to where that is? You'll have to either use Migrations or EnsureCreated (though that's discouraged).
See also the EF getting started guide, where minimal migration creation is shown.

Related

Setting EntityState.Modified during update operation with Entity Framework

Assume that I have the following little console application which uses Entity Framework 5:
class Program {
static void Main(string[] args) {
using (var ctx = new ConfContext()) {
var personBefore = ctx.People.First();
Console.WriteLine(personBefore.Name);
personBefore.Name = "Foo2";
ctx.SaveChanges();
var personAfter = ctx.People.First();
Console.WriteLine(personAfter.Name);
}
Console.ReadLine();
}
}
public class ConfContext : DbContext {
public IDbSet<Person> People { get; set; }
public IDbSet<Session> Sessions { get; set; }
}
public class Person {
[Key]
public int Key { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public DateTime? BirthDate { get; set; }
public ICollection<Session> Sessions { get; set; }
}
public class Session {
[Key]
public int Key { get; set; }
public int PersonKey { get; set; }
public string RoomName { get; set; }
public string SessionName { get; set; }
public Person Person { get; set; }
}
As you can see, I am changing the name of the record and saving it. It works but it feels like magic to me. What I am doing in all of my applications is the following one (to be more accurate, inside the Edit method of my generic repository):
static void Main(string[] args) {
using (var ctx = new ConfContext()) {
var personBefore = ctx.People.First();
Console.WriteLine(personBefore.Name);
personBefore.Name = "Foo2";
var entity = ctx.Entry<Person>(personBefore);
entity.State = EntityState.Modified;
ctx.SaveChanges();
var personAfter = ctx.People.First();
Console.WriteLine(personAfter.Name);
}
Console.ReadLine();
}
There is no doubt that the second one is more semantic but is there any other obvious differences?
Well the second code block where you explicitly set the entity state is redundant, as the change tracker already knows that the entity is modified because the context knows about the entity (as you query the context to retrieve the entity).
Setting (or painting) the state of the entity would be more useful when working with disconnected entities, for example in an n-tier environment where the entity was retrieved in a different context and sent to a client for modification, and you wish to mark those changes back on the server using a different context.
Otherwise, the first code block is cleaner in my opinion.

Exception in lazy loading (Entity Framework)

I use Entity Framework in my project. The issue is well known but supposed solutions (eg. this and this) doesn't work for me.
/// <summary>
/// Returns complete list of lecturers from DB.
/// </summary>
public IEnumerable<Lecturer> GetAllLecturers()
{
IList<Lecturer> query;
using (var dbb = new AcademicTimetableDbContext())
{
query = (from b in dbb.Lecturers select b).ToList();
}
Debug.WriteLine(query[0].AcademicDegree); // Exception (***)
return query;
}
Exception (***):
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
public class Lecturer
{
public Lecturer()
{
this.Timetables = new List<Timetable>();
this.Courses = new List<Course>();
}
public int Id_Lecturer { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Phone_Number { get; set; }
public Nullable<int> Academic_Degree_Id { get; set; }
public virtual AcademicDegree AcademicDegree { get; set; }
public virtual ICollection<Timetable> Timetables { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
What's wrong?
Lazy loading works until your DbContext lives.
With the using you dispose your DbContext so EF will throw an exception when you try to access the navigation properties outside the using block.
You can test this with moving the Debug.WriteLine inside the using block where it won't throw exception:
using (var dbb = new AcademicTimetableDbContext())
{
query = (from b in dbb.Lecturers select b).ToList();
Debug.WriteLine(query[0].AcademicDegree);
}
And the solution is to tell EF to eagerly load the navigation properties with the using Include method:
using (var dbb = new AcademicTimetableDbContext())
{
query = (from b in dbb.Lecturers.Include(l => l.AcademicDegree) select b)
.ToList();
}
Debug.WriteLine(query[0].AcademicDegree);

Why is EF code first throwing model backing context exception? Using 4.0.3

Heres the exception:
The model backing the 'ScannerContext' context has changed since the
database was created. Consider using Code First Migrations to update
the database (http://go.microsoft.com/fwlink/?LinkId=238269).
I get this everytime I run my application. I cant figure out what it means. I think it means something isn't mapped correctly, but I cant figure out what. I am using the code first model, and I have an existing database that I want totally custom mappings for. Right now, I have everything in my classes named the same as my database to eliminate possible cuases.
The Exception is thrown when I try to .Add() the entity to the context.
The Entity as it is in the Database
The Entity in my DataLayer
public class EAsset
{
public int i_GID { get; set; }
public EAssetType Type { get; set; }
public EOrgEnvironment Environment { get; set; }
public EUser Contact { get; set; }
public string s_Name { get; set; }
public string s_Role { get; set; }
public DateTime d_Added { get; set; }
public DateTime d_LastUpdated { get; set; }
public bool b_Retired { get; set; }
public EAsset()
{
Type = new EAssetType();
Environment = new EOrgEnvironment();
Contact = new EUser();
d_Added = DateTime.Now;
d_LastUpdated = DateTime.Now;
}
}
The Context Object (with attempted table mapping and key assignment)
public class ScannerContext : DbContext
{
public ScannerContext()
: base("LabDatabase") { }
public DbSet<EAsset> EAssets { get; set; }
public DbSet<EAssetType> EAssetTypes { get; set; }
public DbSet<EOrgEnvironment> EOrgEnvironments { get; set; }
public DbSet<EUser> EUsers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<EAsset>().HasKey(k=>k.i_GID).ToTable("t_Assets");
modelBuilder.Entity<EAssetType>().HasKey(k => k.i_ID).ToTable("t_Asset_Types");
modelBuilder.Entity<EOrgEnvironment>().HasKey(k => k.i_ID).ToTable("t_Org_Environments");
modelBuilder.Entity<EUser>().HasKey(k => k.i_ID).ToTable("t_Users");
base.OnModelCreating(modelBuilder);
}
}
The Program
class Program
{
static void Main(string[] args)
{
EAsset Entity = new EAsset { s_Name = "jewri-pc" };
var sContext = new ScannerContext();
sContext.EAssets.Add(Entity);
sContext.SaveChanges();
}
}
For EF runtime version 4.0.3 / version 4.0
public class ScannerContext : DbContext
{
public ScannerContext()
: base("LabDatabase") { }
...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<ScannerContext>(null); // <--- This is what i needed
...
base.OnModelCreating(modelBuilder);
}
}
With that code installed I am now chasing errors related to having all my relationships accounted for in the model. The FK Constraints are forcing me to add the missing relational items.
Found info here. They explain the importance a bit.
The model backing the <Database> context has changed since the database was created
Enable-Migrations -ContextTypeName EmployeeProject.Models.DepartmentContext
Means you have to write your project name.Models.Context name
It will work.

Problems using TPT (Table Per Type) in EF 4.2 and deletion of parent objects

From what I understand on several posts the TPT architecure, with EF, does not create the necessary ON DELETE CASCADE when using a shared primary key.... It was also said that the EF context will handle the proper order of deletion of the sub-classed tables (however I do get an error that it breaks the constraint and that I can fix it with adding the ON DELETE CASCADE on the sub-class table)...
more background info...
I have a Section class, which has a number, title, and a list of pages. The page is designed using a super class which holds basic page properties. I have about 10+ sub-classes of the page class. The Section class holds an ICollection of these pages. The DB is created properly with the exception of no ON DELETE CASCADE on the sub-classed tables.
My code will create the entities and adds to the DB fine. However, if I try to delete a section (or all sections) it fails todelete due to the FK constraint on my sub-class page table...
public abstract BaseContent
{
... common properties which are Ignored in the DB ...
}
public class Course : BaseContent
{
public int Id {get;set;}
public string Name {get;set;}
public string Descripiton {get;set;}
public virtual ICollection<Chapter> Chapters{get;set;}
...
}
public class Chapter : BaseContent
{
public int Id {get;set;}
public int Number {get;set;}
public string Title {get;set;}
public virtual Course MyCourse{get;set;}
public virtual ICollection<Section> Sections{get;set;}
...
}
public class Section : BaseContent
{
public int Id {get;set;}
public int Number {get;set;}
public string Title {get;set;}
public virtual Chapter MyChapter {get;set;}
public virtual ICollection<BasePage> Pages {get;set;}
...
}
public abstract class BasePage : BaseContent, IComparable
{
public int Id { get; set; }
public string Title { get; set; }
public string PageImageRef { get; set; }
public ePageImageLocation ImageLocationOnPage { get; set; }
public int PageNumber { get; set; }
public virtual Section MySection { get; set; }
...
}
public class ChapterPage : BasePage
{
public virtual int ChapterNumber { get; set; }
public virtual string ChapterTitle { get; set; }
public virtual string AudioRef { get; set; }
}
public class SectionPage : BasePage
{
public virtual int SectionNumber { get; set; }
public virtual string SectionTitle { get; set; }
public virtual string SectionIntroduction { get; set; }
}
... plus about 8 other BasePage sub-classes...
public class MyContext: DbContext
{
...
public DbSet<Course> Courses { get; set; }
public DbSet<Chapter> Chapters { get; set; }
public DbSet<Section> Sections { get; set; }
public DbSet<BasePage> Pages { get; set; }
...
}
.. Fluent API ... (note Schema is defined to "" for SqlServer, for Oracle its the schema name)
private EntityTypeConfiguration<T> configureTablePerType<T>(string tableName) where T : BaseContent
{
var config = new EntityTypeConfiguration<T>();
config.ToTable(tableName, Schema);
// This adds the appropriate Ignore calls on config for the base class BaseContent
DataAccessUtilityClass.IgnoreAllBaseContentProperties<T>(config);
return config;
}
public virtual EntityTypeConfiguration<BasePage> ConfigurePageContent()
{
var config = configureTablePerType<BasePage>("PageContent");
config.HasKey(pg => pg.Id);
config.HasRequired(pg => pg.Title);
config.HasOptional(pg => pg.PageImageRef);
config.Ignore(pg => pg.ImageLocationOnPage);
return config;
}
public virtual EntityTypeConfiguration<ChapterPage> ConfigureChapterPage()
{
var config = configureTablePerType<ChapterPage>("ChapterPage");
config.HasOptional(pg => pg.AudioRef);
config.Ignore(pg => pg.ChapterNumber);
config.Ignore(pg => pg.ChapterTitle);
return config;
}
public virtual EntityTypeConfiguration<SectionPage> ConfigureSectionPage()
{
var config = configureTablePerType<SectionPage>("SectionPage");
config.HasOptional(pg => pg.AudioRef);
config.Ignore(pg => pg.SectionNumber);
config.Ignore(pg => pg.SectionTitle);
return config;
}
... other code to model other tables...
So the app is able to populate content and the relationships are properly set up. However, when I try to delete the course, I get the error that the delete failed due to the constraint on the ChapterPage to PageContent table..
Here is the code which deletes the Course (actually I delete all courses)...
using (MyContext ctx = new MyContext())
{
ctx.Courses.ToList().ForEach(crs => ctx.Courses.Remove(crs));
AttachLookupEntities(ctx);
ctx.SaveChanges();
}
If I add the 'ON DELETE CASCADE' in the ChapterPage and SectionPage table for its shared primary with PageContent, the delete goes through.
In summary,
The only solution that I have seen is to manually alter the constraints to add the ON DELETE CASCADE for all of my sub-class page tables. I can implement the change, as I have code which generates the DB script for the EF tables I need (a small subset of our whole DB) since we will not use EF to create or instantiate the DB (since it does not properly support migrations as yet...).
I sincerely hope that I have miscoded something, or forgot some setting in the model builder logic. Because if not, the EF designers have defined an architecure (TPT design approach) which cannot be used in any real world situation without a hack workaround. It's a half finished solution. Do not get me wrong, I like the work that has been done, and like most MSFT solutions its works for 70% of most basic application usages. It just is not ready for more complex situations.
I was trying to keep the DB design all within the EF fluent API and self-contained. It's about 98% there for me, just would be nice if they finished the job, maybe in the next release. At least it saves me all the CRUD operations.
Ciao!
Jim Shaw
I have reproduced the problem with a little bit simpler example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
namespace EFTPT
{
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<BasePage> Pages { get; set; }
}
public abstract class BasePage
{
public int Id { get; set; }
public string Name { get; set; }
public Parent Parent { get; set; }
}
public class DerivedPage : BasePage
{
public string DerivedName { get; set; }
}
public class MyContext : DbContext
{
public DbSet<Parent> Parents { get; set; }
public DbSet<BasePage> BasePages { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Parent>()
.HasMany(p => p.Pages)
.WithRequired(p => p.Parent); // creates casc. delete in DB
modelBuilder.Entity<BasePage>()
.ToTable("BasePages");
modelBuilder.Entity<DerivedPage>()
.ToTable("DerivedPages");
}
}
class Program
{
static void Main(string[] args)
{
using (var ctx = new MyContext())
{
var parent = new Parent { Pages = new List<BasePage>() };
var derivedPage = new DerivedPage();
parent.Pages.Add(derivedPage);
ctx.Parents.Add(parent);
ctx.SaveChanges();
}
using (var ctx = new MyContext())
{
var parent = ctx.Parents.FirstOrDefault();
ctx.Parents.Remove(parent);
ctx.SaveChanges(); // exception here
}
}
}
}
This gives the same exception that you had too. Only solutions seem to be:
Either setup cascading delete for the TPT constraint in the DB manually, as you already tested (or put an appropriate SQL command into the Seed method).
Or load the entites which are involved in the TPT inheritance into memory. In my example code:
var parent = ctx.Parents.Include(p => p.Pages).FirstOrDefault();
When the entities are loaded into the context, EF creates actually two DELETE statements - one for the base table and one for the derived table. In your case, this is a terrible solution because you had to load a much more complex object graph before you can get the TPT entities.
Even more problematic is if Parent has an ICollection<DerivedPage> (and the inverse Parent property is in DerivedPage then):
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<DerivedPage> Pages { get; set; }
}
public abstract class BasePage
{
public int Id { get; set; }
public string Name { get; set; }
}
public class DerivedPage : BasePage
{
public string DerivedName { get; set; }
public Parent Parent { get; set; }
}
The example code wouldn't throw an exception but instead delete the row from the derived table but not from the base table, leaving a phantom row which cannot represent an entity anymore because BasePage is abstract. This problem is not solvable by a cascading delete but you were actually forced to load the collection into the context before you can delete the parent to avoid such a nonsense in the database.
A similar question and analysis was here: http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/3c27d761-4d0a-4704-85f3-8566fa37d14e/

Entity Framework, Code First, Update "one to many" relationship with independent associations

It took me way too long to find a solution to the scenario described below. What should seemingly be a simple affair proved to be rather difficult. The question is:
Using Entity Framework 4.1 (Code First approach) and "Independent associations" how do I assign a different end to an existing "many to one" relationship in a "detached" scenario ( Asp.Net in my case).
The model:
I realize that using ForeignKey relationships instead of Independent Associations would have been an option, but it was my preference to not have a ForeignKey implementation in my Pocos.
A Customer has one or more Targets:
public class Customer:Person
{
public string Number { get; set; }
public string NameContactPerson { get; set; }
private ICollection<Target> _targets;
// Independent Association
public virtual ICollection<Target> Targets
{
get { return _targets ?? (_targets = new Collection<Target>()); }
set { _targets = value; }
}
}
A Target has one Customer:
public class Target:EntityBase
{
public string Name { get; set; }
public string Description { get; set; }
public string Note { get; set; }
public virtual Address Address { get; set; }
public virtual Customer Customer { get; set; }
}
Customer derives from a Person class:
public class Person:EntityBase
{
public string Salutation { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set ; }
public string Telephone1 { get; set; }
public string Telephone2 { get; set; }
public string Email { get; set; }
public virtual Address Address { get; set; }
}
EntityBase class provides some common properties:
public abstract class EntityBase : INotifyPropertyChanged
{
public EntityBase()
{
CreateDate = DateTime.Now;
ChangeDate = CreateDate;
CreateUser = HttpContext.Current.User.Identity.Name;
ChangeUser = CreateUser;
PropertyChanged += EntityBase_PropertyChanged;
}
public void EntityBase_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (Id != new Guid())
{
ChangeDate = DateTime.Now;
ChangeUser = HttpContext.Current.User.Identity.Name;
}
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, e);
}
public event PropertyChangedEventHandler PropertyChanged;
public Guid Id { get; set; }
public DateTime CreateDate { get; set; }
public DateTime? ChangeDate { get; set; }
public string CreateUser { get; set; }
public string ChangeUser { get; set; }
}
The Context:
public class TgrDbContext : DbContext
{
public DbSet<Person> Persons { get; set; }
public DbSet<Address> Addresses { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Target> Targets { get; set; }
public DbSet<ReportRequest> ReportRequests { get; set; }
// If OnModelCreating becomes to big, use "Model Configuration Classes"
//(derived from EntityTypeConfiguration) instead
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>().HasOptional(e => e.Address);
modelBuilder.Entity<Customer>().HasMany(c => c.Targets).WithRequired(t => t.Customer);
}
public static ObjectContext TgrObjectContext(TgrDbContext tgrDbContext)
{
return ((IObjectContextAdapter)tgrDbContext).ObjectContext;
}
}
I waited for #Martin answer because there are more solutions for this problem. Here is another one (at least it works with ObjectContext API so it should work with DbContext API as well):
// Existing customer
var customer = new Customer() { Id = customerId };
// Another existing customer
var customer2 = new Customer() { Id = customerId2 };
var target = new Target { ID = oldTargetId };
// Make connection between target and old customer
target.Customer = customer;
// Attach target with old customer
context.Targets.Attach(target);
// Attach second customer
context.Customers.Attach(customer2);
// Set customer to a new value on attached object (it will delete old relation and add new one)
target.Customer = customer2;
// Change target's state to Modified
context.Entry(target).State = EntityState.Modified;
context.SaveChanges();
The problem here is internal state model and state validations inside EF. Entity in unchanged or modified state with mandatory relation (on many side) cannot have independent association in added state when there is no other in deleted state. Modified state for association is not allowed at all.
There is a lot of information to be found on this topic; on stackoverflow I found Ladislav Mrnka's insights particularly helpful. More on the subject can also be found here: NTier Improvements for Entity Framework and here What's new in Entity Framework 4?
In my project (Asp.Net Webforms) the user has the option to replace the Customer assigned to a Target object with a different (existing) Customer object. This transaction is performed by a FormView control bound to an ObjectDataSource. The ObjectDataSource communicates with the BusinessLogic layer of the project which in turns passes the transaction to a repository class for the Target object in the DataAccess layer. The Update method for the Target object in the repository class looks like this:
public void UpdateTarget(Target target, Target origTarget)
{
try
{
// It is not possible to handle updating one to many relationships (i.e. assign a
// different Customer to a Target) with "Independent Associations" in Code First.
// (It is possible when using "ForeignKey Associations" instead of "Independent
// Associations" but this brings about a different set of problems.)
// In order to update one to many relationships formed by "Independent Associations"
// it is necessary to resort to using the ObjectContext class (derived from an
// instance of DbContext) and 'manually' update the relationship between Target and Customer.
// Get ObjectContext from DbContext - ((IObjectContextAdapter)tgrDbContext).ObjectContext;
ObjectContext tgrObjectContext = TgrDbContext.TgrObjectContext(_tgrDbContext);
// Attach the original origTarget and update it with the current values contained in target
// This does NOT update changes that occurred in an "Independent Association"; if target
// has a different Customer assigned than origTarget this will go unrecognized
tgrObjectContext.AttachTo("Targets", origTarget);
tgrObjectContext.ApplyCurrentValues("Targets", target);
// This will take care of changes in an "Independent Association". A Customer has many
// Targets but any Target has exactly one Customer. Therefore the order of the two
// ChangeRelationshipState statements is important: Delete has to occur first, otherwise
// Target would have temporarily two Customers assigned.
tgrObjectContext.ObjectStateManager.ChangeRelationshipState(
origTarget,
origTarget.Customer,
o => o.Customer,
EntityState.Deleted);
tgrObjectContext.ObjectStateManager.ChangeRelationshipState(
origTarget,
target.Customer,
o => o.Customer,
EntityState.Added);
// Commit
tgrObjectContext.Refresh(RefreshMode.ClientWins, origTarget);
tgrObjectContext.SaveChanges();
}
catch (Exception)
{
throw;
}
}
This works for the Update method for the Target object. Remarkably, the procedure for inserting a new Target object is way easier. DbContext recognizes the Customer end of the independent association properly and commits the change to the database without further ado. The Insert method in the repository class looks like this:
public void InsertTarget(Target target)
{
try
{
_tgrDbContext.Targets.Add(target);
_tgrDbContext.SaveChanges();
}
catch (Exception)
{
throw;
}
}
Hopefully this will be useful to somebody dealing with a similar task. If you notice a problem with this approach described above, please let me know in your comments. Thanks!