I have using .net Core 3.1 scaffolded Identity and extended that with my own classes. But when I use the build in DeletePersonalData.OnPostAsync() it fails due to my relations from my other classes. I don't get how I make the delete to delete all the extended classes too.
Error message:
SqlException: The DELETE statement conflicted with the REFERENCE
constraint "FK_Workspaces_AspNetUsers_OwnerId". The conflict occurred
in database "myupload", table "dbo.Workspaces", column 'OwnerId'. The
statement has been terminated.
Microsoft.Data.SqlClient.SqlCommand+<>c.b__164_0(Task
result)
Extended Identity:
public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<MyFile> MyFiles { get; set; }
public DbSet<Workspace> Workspaces { get; set; }
public DbSet<WorkspacePermission> WorkspacePermissions { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
builder.Entity<Workspace>()
.HasOne(p => p.Owner)
.WithMany()
.OnDelete(DeleteBehavior.Cascade);
builder.Entity<MyFile>()
.HasOne(p => p.Workspace)
.WithMany(b => b.MyFile);
}
}
And the delete method:
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
RequirePassword = await _userManager.HasPasswordAsync(user);
if (RequirePassword)
{
if (!await _userManager.CheckPasswordAsync(user, Input.Password))
{
ModelState.AddModelError(string.Empty, "Incorrect password.");
return Page();
}
}
var result = await _userManager.DeleteAsync(user);
var userId = await _userManager.GetUserIdAsync(user);
if (!result.Succeeded)
{
throw new InvalidOperationException($"Unexpected error occurred deleting user with ID '{userId}'.");
}
await _signInManager.SignOutAsync();
_logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId);
return Redirect("~/");
}
}
One of the Classes:
public class Workspace
{
// Base
public Guid WorkspaceID { get; set; }
public string Name { get; set; }
// Security
public virtual IdentityUser Owner { get; set; }
public string Password { get; set; }
// Files
public virtual ICollection<MyFile> MyFile { get; set; }
// Statistics
public Workspace()
{
}
}
Using Fluent API I managed to add the Cascade Delete to the IdentityUser with this Code in the OnModelCreating method.
builder.Entity<Workspace>()
.HasOne(p => p.Owner)
.WithMany()
.OnDelete(DeleteBehavior.Cascade);
builder.Entity<MyFile>()
.HasOne(p => p.Workspace)
.WithMany(b => b.MyFile);
Related
I'm using last version of json implementation in Pomelo 5.0 and configure my maria server to use microsoft json serialisation.
var serverVersion = new MariaDbServerVersion(new Version(10, 3, 0));
services.AddDbContext<BusinessManagementDbContext>(options =>
{
options.UseMySql(databaseConfiguration.ConnectionString, serverVersion, m =>
{
m.UseMicrosoftJson(MySqlCommonJsonChangeTrackingOptions.FullHierarchyOptimizedSemantically);
m.EnableRetryOnFailure();
});
options.EnableSensitiveDataLogging(true);
});
I can save my POCO in my db but when I try to query my data, I get a null object.
Here's my data :
HeidySQL data
My query is pretty simple but I think I'm not using the right way for json query.
await Context.ValidatedSaleInvoices.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);
It seems like there is no deserialization between my data and my property "Content".
How can I do this ?
Thank you,
Edit
My model is :
public class ValidateSaleInvoiceEntity
{
public int Id { get; set; }
public ValidateSaleInvoiceContent Content { get; set; }
}
public class ValidateSaleInvoiceContent
{
public string BusinessName { get; set; }
public DateTime Date { get; internal set; }
public string Number { get; internal set; }
public Address Address { get; internal set; }
public List<ValidateSaleInvoiceLineEntity> Lines { get; internal set; } = new List<ValidateSaleInvoiceLineEntity>();
}
public class ValidateSaleInvoiceLineEntity
{
public string Description { get; internal set; }
public decimal Quantity { get; internal set; }
public decimal UnitPriceVatExcluded { get; internal set; }
public decimal VatRate { get; internal set; }
}
And my json Result was like this (empty, like there waere no deserialisation: { "BusinessName":"", "Date":"", "Number":"" etc.}
My boss stop my poc about MariaDB Json implementation so I had to go back to this good old friend pure sql column :/ . That's why I haven"t a full json result. Sorry
For a property to serialize/deserialize JSON automatically to a POCO, you need to tell Pomelo, that the table column of the property is of the MySQL/MariaDB type json:
public class ValidateSaleInvoiceEntity
{
public int Id { get; set; }
[Column(TypeName = "json")] // <-- this is one way to do it
public ValidateSaleInvoiceContent Content { get; set; }
}
public class MyContext : DbContext
{
// ...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ValidateSaleInvoiceEntity>()
.Property(e => e.Content)
.HasColumnType("json"); // <-- this is another way to do it
}
}
Here is a fully working console project:
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace IssueConsoleTemplate
{
// EF Core entities:
public class IceCream
{
public int IceCreamId { get; set; }
public string Name { get; set; }
// Either use this data annotation, or the corresponding Fluent API call (see
// OnModelCreating), to explicitly mark the column type as JSON.
[Column(TypeName = "json")]
public IceCreamDetails Details { get; set; }
}
// JSON class:
public class IceCreamDetails
{
public int Kilojoule { get; set; }
public int Rating { get; set; }
}
public class Context : DbContext
{
public DbSet<IceCream> IceCreams { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
var connectionString = "server=127.0.0.1;port=3306;user=root;password=;database=So68020732";
var serverVersion = ServerVersion.AutoDetect(connectionString);
optionsBuilder.UseMySql(connectionString, serverVersion, options => options
.UseMicrosoftJson(MySqlCommonJsonChangeTrackingOptions.FullHierarchyOptimizedSemantically))
.UseLoggerFactory(
LoggerFactory.Create(
configure => configure
.AddConsole()
.AddFilter(level => level >= LogLevel.Information)))
.EnableSensitiveDataLogging()
.EnableDetailedErrors();
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<IceCream>(
entity =>
{
// Either use this Fluent API call, or the corresponding data annotation
// (see the IceCreamDetails class), to explicitly mark the column type as JSON.
entity.Property(e => e.Details)
.HasColumnType("json");
entity.HasData(
new IceCream {IceCreamId = 1, Name = "Vanilla", Details = new IceCreamDetails { Kilojoule = 865, Rating = 9 }},
new IceCream {IceCreamId = 2, Name = "Chocolate", Details = new IceCreamDetails { Kilojoule = 903, Rating = 10 }});
});
}
}
internal static class Program
{
private static void Main()
{
using var context = new Context();
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var iceCreams = context.IceCreams
.OrderBy(i => i.IceCreamId)
.ToList();
Trace.Assert(iceCreams.Count == 2);
Trace.Assert(iceCreams[0].Details.Kilojoule == 865);
Trace.Assert(iceCreams[1].Details.Rating == 10);
}
}
}
You can find the most comprehensive JSON sample code on our repository (see the JSON mapping and query scenarios section).
I'm using Entity Framework Core 2.1.2 with lazy loading enabled and am performing a query. If I try to pass a lambda expression I always get the following exception:
System.InvalidOperationException: Error generated for warning
'Microsoft.EntityFrameworkCore.Infrastructure.DetachedLazyLoadingWarning:
An attempt was made to lazy-load navigation property 'Children' on
detached entity of type 'ParentProxy'. Lazy-loading is not supported
for detached entities or entities that are loaded with
'AsNoTracking()'.'
Here some code :
public class User
{
public virtual ICollection<UserRole> UserRoles { get; set; } = new HashSet<UserRole>();
}
public class UserRole
{
public int UserId { get; set; }
public int RoleId { get; set; }
public virtual User User { get; set; }
}
My db context:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddDbContext<Context>(options =>
{
options.UseLazyLoadingProxies();
options.UseSqlServer(Configuration.GetConnectionString("connection"));
});
}
That's how it works:
_userRepository.Table.Where(user => user.UserRoles.Any(userRole => userRole.RoleId == 10)).ToList()
And that's how it doesn't:
_userRepository.Table.Where(user => condition(user)).ToList()
Where the condition is:
Func<User, bool> condition
Example:
Func<User, bool> result = (user) => user.UserRoles.Any(role => role.RoleId == 10)
I'm so sorry for bad formatting. But I hope that you understand my problem.
1) i have Enttiy Class In which have three tables whose code is below given
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Web;
namespace GridWithInlineEdit.Models
{
#region ENTITY BLOCK
[Table("TBLUSER", Schema = "orient")]
public class Users
{
public Users()
{
UsersDetailCollection = new List<Usersdetail>();
}
//
[Key, Column("UID", TypeName = "INT")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Uid { get; set; }
[Required]
[StringLength(50, MinimumLength = 10, ErrorMessage = "Please Enter {0} Upto 50 Characters!")]
[RegularExpression(#"(\S)+", ErrorMessage = "White space is not allowed here!")]
[Column("FNAME", TypeName = "nvarchar")]
public string Fname { get; set; }
[Required]
[StringLength(100, MinimumLength = 10, ErrorMessage = "Please Enter {0} Upto 50 Characters!")]
[RegularExpression(#"(\S)+", ErrorMessage = "White space is not allowed here!")]
[Column("LNAME", TypeName = "nvarchar")]
public string Lname { get; set; }
public ICollection<Usersdetail> UsersDetailCollection { get; set; }
}
[Table("TBLUSERDETAIL", Schema = "orient")]
public class Usersdetail
{
public Usersdetail()
{
CountryCollection = new List<Countries>();
}
[Key, Column("ID", TypeName = "INT")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[StringLength(100)]
[Column("EMAIL", TypeName = "VARCHAR")]
public String Email { get; set; }
[StringLength(11)]
[Column("PHONE", TypeName = "VARCHAR")]
public String Phone { get; set; }
[Required]
public int? UserId { get; set; }
[ForeignKey("UserId"), Column("UID", TypeName = "INT")]
public virtual Users Users { get; set; }
[Required]
public int? CountryId { get; set; }
[ForeignKey("CountryId"), Column("CID", TypeName = "INT")]
public virtual Countries Countries { get; set; }
public ICollection<Countries> CountryCollection { get; set; }
}
[Table("TBLCOUNTRY", Schema = "orient")]
public class Countries
{
[Key, Column("CID", TypeName = "INT")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Cid { get; set; }
[StringLength(50)]
[RegularExpression(#"(\S)+", ErrorMessage = "White space is not allowed here!")]
[Column("CNAME", TypeName = "VARCHAR")]
public String Cname { get; set; }
}
#endregion
#region ENTITY MAPPING BLOCK
public class UserMap : EntityTypeConfiguration<Users>
{
#region Constructors and Destructors
internal UserMap()
{
// Primary Key
HasKey(t => t.Uid);
Property(p => p.Uid).HasColumnName("UID").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();
// Table & Column Mappings
ToTable("TBLUSER");
Property(t => t.Fname).HasColumnName("FNAME").HasMaxLength(50);
Property(t => t.Lname).HasColumnName("LNAME").HasMaxLength(50);
}
#endregion
}
public class UserDetailMap : EntityTypeConfiguration<Usersdetail>
{
#region Constructors and Destructors
internal UserDetailMap()
{
// Primary Key
HasKey(t => t.ID);
HasKey(t => t.UserId);
HasKey(t => t.CountryId);
// Properties
Property(t => t.Email).HasMaxLength(100);
Property(t => t.Phone).HasMaxLength(11);
// Column Mappings
ToTable("TBLUSERDETAIL");
Property(t => t.ID).HasColumnName("ID").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();
Property(t => t.Email).HasColumnName("EMAIL");
Property(t => t.Phone).HasColumnName("PHONE");
Property(t => t.UserId).HasColumnName("UID");
Property(t => t.CountryId).HasColumnName("CID");
// Relationships
HasOptional(t => t.Users).WithMany().HasForeignKey(d => d.UserId);
HasOptional(t => t.Countries).WithMany().HasForeignKey(d => d.CountryId);
}
#endregion
}
public class CountryMap : EntityTypeConfiguration<Countries>
{
#region Constructors and Destructors
internal CountryMap()
{
// Primary Key
HasKey(t => t.Cid);
// Properties
Property(t => t.Cname).HasMaxLength(50);
// Column Mappings
Property(t => t.Cid).HasColumnName("CID").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();
Property(t => t.Cname).HasColumnName("CNAME");
}
#endregion
}
#endregion
}
2) Second is Init Class in which have connection string custom with sqlserver 2005
Connection string class code is below given
using System;
using System.Data.Common;
using System.Data.Entity.Infrastructure;
namespace GridWithInlineEdit.Models
{
public static class Constants
{
public static string ConnectionString
{
get { return GetDecryptedConnectionString(); }
}
private static string GetDecryptedConnectionString()
{
return #"Data Source=193.193.193.254;Initial Catalog=EFCFUsersdb;;USER ID=sa;PASSWORD=123;Persist Security Info=True";
}
}
class EncryptedIDbConnectionFactory : IDbConnectionFactory
{
#region Private Fields
IDbConnectionFactory _connectionFactory;
#endregion
#region Constructors
public EncryptedIDbConnectionFactory(IDbConnectionFactory dbConnectionFactory)
{
if (dbConnectionFactory == null)
{
throw new ArgumentNullException("dbConnectionFactory can not be null");
}
_connectionFactory = dbConnectionFactory;
}
#endregion
#region IDbConnectionFactory implementation
public DbConnection CreateConnection(string nameOrConnectionString)
{
//decryption of connection string
string decryptedConnectionString =
GetDecryptedConnectionString(nameOrConnectionString);
return _connectionFactory.CreateConnection(decryptedConnectionString);
}
#endregion
#region Private Methods
private string GetDecryptedConnectionString(string nameOrConnectionString)
{
//use some encryption library to decrypt
return nameOrConnectionString;
}
#endregion
}
}
and Init class is below given
using System.Data.Entity;
namespace GridWithInlineEdit.Models
{
public class Init : DropCreateDatabaseIfModelChanges<SampleContext>
{
protected override void Seed(SampleContext context)
{
base.Seed(context);
//context.Locations.Add(new Location() { LocationName = "Khanna, LDH" });
//context.Sessions.Add(new Session() { SessionName = "Entity Framework" });
context.SaveChanges();
}
}
}
3 ) this is samplecontext class code
using System.Data.Entity;
using System.Data.SqlClient;
namespace GridWithInlineEdit.Models
{
public class SampleContext : DbContext
{
public SampleContext()
: base(new SqlConnection(Constants.ConnectionString) ,false)
//Data Source=193.193.193.254;Initial Catalog=EFCFUsersdb;Persist Security Info=True;User ID=sa;Password=123
{
Configuration.ProxyCreationEnabled = true;
Configuration.AutoDetectChangesEnabled = true;
}
public DbSet<Users> User { get; set; }
public DbSet<Usersdetail> UserDetail { get; set; }
public DbSet<Countries> Country { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new UserMap());
modelBuilder.Configurations.Add(new UserDetailMap());
modelBuilder.Configurations.Add(new CountryMap());
}
}
}
4) in Global file of application have below code
using System.Data.Entity;
using System.Web.Mvc;
using System.Web.Routing;
using GridWithInlineEdit.Models;
namespace GridWithInlineEdit
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "User", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
//Database.DefaultConnectionFactory = new EncryptedIDbConnectionFactory(Database.DefaultConnectionFactory);
Database.SetInitializer<SampleContext>(new Init());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}
In My Home Controller have below given code
> 1. using System.Web.Mvc; using GridWithInlineEdit.Models;
>
> namespace GridWithInlineEdit.Controllers {
> public class UserController : Controller
> {
>
>
> public ActionResult Index()
> {
> var db = new SampleContext();
> return View();
> }
>
> [HttpPost]
> public ActionResult Create()
> {
>
> //return View();
> return null;
> }
>
> } }
Now the problem is this whenever run my application database is not created and show exception server version property when i see through add watch in _db object by putting breakpoint on index action result.
pls pls resolve or give solution i have tried for this many time but i am confused why this happening
I know you have in the comments above that you applied a Windows Server patch and got it working, but with looking at your project, I had some observations:
There is nothing in your "Create" method in your controller for adding
new records
There is no "Read" method for returning data to anything
that might want to read data, such as a Kendo grid.
There is no "Delete" method for removing data records.
I'm not sure what the UserMap, DetailMap, and CountryMap are used for, along with your "RegisterRoutes", etc. on Application_Start -- these seem like a severe case of overcomplicating things, to me.
No View (presentation layer) code posted.
Maybe you fixed the Create, Read, and Delete routines later when you got it working, and maybe the UserMap, DetailMap, CountryMap, and Init all were for something, but be damned if I could make heads-or-tails of what you were doing. I saw no View code, grid or otherwise, that you were pulling your data into. When asking for help, just saying, context is everything.
While you would need to obtain and install Telerik's Kendo UI MVC components, it might be worth it to you to look at this blog for setting up the entity framework in MVC and preparing a grid for receiving data:
http://docs.telerik.com/kendo-ui/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/ajax-binding
When I call context.SaveChanges() to update a specific product, the update is not registered in the database. I do not get any runtime error either. All I notice is that my product catalog is not updated. I still see the same values. When I run the debugger I notice that the connection state of the database is closed.
This is the class implementing the context.SaveChanges()
namespace SportsStore.Domain.Concrete
{
public class EFProductRepository : IProductRepository
{
private EFDbContext context = new EFDbContext();
public IQueryable<Product> Products
{
get { return context.Products; }
}
public void SaveProduct(Product product)
{
if (product.ProductID == 0)
{
context.Products.Add(product);
}
context.SaveChanges();
}
}
}
namespace SportsStore.Domain.Concrete
{
public class EFDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
}
}
namespace SportsStore.Domain.Entities
{
public class Product
{
[HiddenInput(DisplayValue=false)]
public int ProductID { get; set; }
public string Name { get; set; }
[DataType(DataType.MultilineText)]
public string Description { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
}
In the EFProductRepository class, prior to calling the context.SaveChanges() method in the SaveProduct method, you can use one of the following approaches to persist changes to the database.
public void SaveProduct(Product product)
{
if (product.ProductID == 0)
{
context.Products.Add(product);
}
//One approach to persist changes to database
//var productInDB = context.Products.Single(x => x.ProductID ==product.ProductID);
//context.Entry(productInDB).CurrentValues.SetValues(product);
//context.SaveChanges();
//Alternate Approach
if (product.ProductID != 0)
{
context.Entry(product).State = System.Data.EntityState.Modified;
}
context.SaveChanges();
}
Given the following simplified model:
public class Account
{
public Account()
{
Id = Guid.NewGuid();
ContactCard = new ContactCard();
}
//[ForeignKey("ContactCard")]
public Guid Id { get; set; }
public string Name { get; set; }
public string Number { get; set; }
public ContactCard ContactCard { get; set; }
}
public class ContactCard
{
public ContactCard()
{
Id = Guid.NewGuid();
}
public Guid Id { get; set; }
public Account Account { get; set; }
}
public class MightDbContext: DbContext
{
public DbSet<Account> Accounts { get; set; }
public DbSet<ContactCard> ContactCards { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Account>().HasRequired(x => x.ContactCard).WithOptional(x => x.Account);
}
}
public class MightDbInitializer : DropCreateDatabaseIfModelChanges<MightDbContext>
{
protected override void Seed(MightDbContext context)
{
var accounts = new List<Account>
{
new Account()
{
Name = "Acme Corporation Pty. Ltd.",
Number = "001ABC"
},
new Account()
{
Name = "Three Little Pigs Pty. Ltd.",
Number = "002DEF"
}
};
accounts.ForEach(c => context.Accounts.Add(c));
}
}
And the following simple console program to iterate the contents of the Accounts and ContactCards collections:
static void Main(string[] args)
{
Database.SetInitializer<MightDbContext>(new MightDbInitializer());
using (var context = new MightDbContext())
{
foreach (Account c in context.Accounts)
{
Console.WriteLine(c.ContactCard.Id);
}
var contactCards = context.ContactCards.ToList(); /* ERROR OCCURS HERE */
foreach (ContactCard a in contactCards)
{
Console.WriteLine(a.Id);
}
}
Console.Read();
}
Why do I get the following error as soon as I try to access the ContactCards collection:
Multiplicity constraint violated. The role 'Account_ContactCard_Source' of the relationship 'InvestAdmin.Might.DataAccess.Account_ContactCard' has multiplicity 1 or 0..1.
When I look at the data that has actually been stored in the database tables all seems to be correct. In fact here is that data:
Accounts:
Id Name Number
ab711bad-1b32-42ca-b68b-12f7be831bd8 Acme Corporation Pty. Ltd. 001ABC
dc20a1dd-0ed4-461d-bc9c-04a85b555740 Three Little Pigs Pty. Ltd. 002DEF
ContactCards:
Id
dc20a1dd-0ed4-461d-bc9c-04a85b555740
ab711bad-1b32-42ca-b68b-12f7be831bd8
And for completeness here is the Account_ContactCard foreign key constraint as defined in the database:
-- Script Date: 06/12/2011 7:00 AM - Generated by ExportSqlCe version 3.5.1.7
ALTER TABLE [Accounts] ADD CONSTRAINT [Account_ContactCard] FOREIGN KEY ([Id]) REFERENCES [ContactCards]([Id]) ON DELETE NO ACTION ON UPDATE NO ACTION;
I have been reading all I can on defining one to one relationships in Code First and have tried many different configurations. All end up back at the same problem.
I found that I could resolve this problem by moving the creation of the associated ContactCard from the Account constructor into the actual creation of the Account objects in the Seed method of the DBInitializer. So it appears that it was not (directly) a problem with the One to One relationship.