将实体添加到数据上下文

时间:2016-11-07 09:55:50

标签: c# entity-framework

我的实体关系就像客户>地址>联系方式。每个客户可能有多个地址,每个地址可能有多个联系人。

我的实体POCO类如

public class CustomerBase
{
    public int CustomerID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [NotMapped]
    public string Address1 { get; set; }

    [NotMapped]
    public string Address2 { get; set; }

    [NotMapped]
    public string Phone { get; set; }

    [NotMapped]
    public string Fax { get; set; }

}

public class Customer : CustomerBase
{
    public virtual List<Addresses> Addresses { get; set; }
}

public class Addresses
{
    [Key]
    public int AddressID { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public bool IsDefault { get; set; }
    public int SerialNo { get; set; }
    public virtual List<Contacts> Contacts { get; set; }

    public int CustomerID { get; set; }
    //[ForeignKey("CustomerID")]
    public virtual Customer Customer { get; set; }
}

public class Contacts
{
    [Key]
    public int ContactID { get; set; }

    public string Phone { get; set; }
    public string Fax { get; set; }
    public bool IsDefault { get; set; }
    public int SerialNo { get; set; }
    public int AddressID { get; set; }

    //[ForeignKey("AddressID")]
    public virtual Addresses Customer { get; set; } 

}

我的数据库上下文看起来像

public class TestDBContext : DbContext
{
    public TestDBContext()
        : base("name=TestDBContext")
    {
        //((IObjectContextAdapter)this).ObjectContext.SavingChanges += new EventHandler(objContext_SavingChanges);
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //modelBuilder.Configurations.Add(new vwCustomerConfiguration());
        Database.SetInitializer<TestDBContext>(null);
    }

    public DbSet<Customer> Customer { get; set; }
    public DbSet<Addresses> Addresses { get; set; }
    public DbSet<Contacts> Contacts { get; set; }
    public virtual DbSet<vwCustomer> vwCustomers { get; set; }
    public DbSet<vwMyCustomers> vwMyCustomers { get; set; }
}

现在这里是更新父代码,并将新的子数据插入地址和联系表。

    using (var db = new TestDBContext())
    {
        //db.Database.Log = s => MyLogger.Log("EFApp", s);

        var existingCustomer = db.Customer
        .Include(a => a.Addresses.Select(x => x.Contacts))
        .FirstOrDefault(p => p.CustomerID == 5);

        existingCustomer.FirstName = "New Customer";

        existingCustomer.Addresses.Where(a => a.AddressID == 5).ToList().ForEach(r => db.Addresses.Remove(r));
        existingCustomer.Addresses.Where(a => a.AddressID == 5).SelectMany(ad => ad.Contacts).Where(c=> c.ContactID==5).ToList().ForEach(r => db.Contacts.Remove(r));

        Addresses oAdrModel = new Addresses();
        oAdrModel.Address1 = "New test xxx";
        oAdrModel.Address2 = "New test xxx";
        oAdrModel.SerialNo = 3;
        oAdrModel.IsDefault = true;
        //oAdrModel.CustomerID = 5;
        existingCustomer.Addresses.Add(oAdrModel);
        //db.Addresses.Add(oAdrModel);
        //db.SaveChanges();
        //int CurAddressID = oAdrModel.AddressID;

        Contacts ContactModel = new Contacts();
        ContactModel.Phone = "New XX-1111111-33";
        ContactModel.Fax = "New XX-1-1111111";
        ContactModel.SerialNo = 4;
        ContactModel.IsDefault = true;
        oAdrModel.Contacts.Add(ContactModel);

        //ContactModel.AddressID = CurAddressID;
        //db.Contacts.Add(ContactModel);

        db.SaveChanges();
    }

oAdrModel.Contacts.Add(ContactModel);抛出错误称为对象引用未设置为对象的实例。只是不明白代码中的错误是什么。

这种方式现在已修复

        oAdrModel.Contacts = new List<Contacts>();
        Contacts ContactModel = new Contacts();
        ContactModel.Phone = "New XX-1111111-33";
        ContactModel.Fax = "New XX-1-1111111";
        ContactModel.SerialNo = 4;
        ContactModel.IsDefault = true;
        oAdrModel.Contacts.Add(ContactModel);

1 个答案:

答案 0 :(得分:0)

完整的工作代码。

域类

public class CustomerBase
{
    public int CustomerID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [NotMapped]
    public string Address1 { get; set; }

    [NotMapped]
    public string Address2 { get; set; }

    [NotMapped]
    public string Phone { get; set; }

    [NotMapped]
    public string Fax { get; set; }

}

public class Customer : CustomerBase
{
    public virtual List<Addresses> Addresses { get; set; }
}

public class Addresses
{
    [Key]
    public int AddressID { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public bool IsDefault { get; set; }
    public int SerialNo { get; set; }
    public virtual List<Contacts> Contacts { get; set; }

    public int CustomerID { get; set; }
    //[ForeignKey("CustomerID")]
    public virtual Customer Customer { get; set; }
}

public class Contacts
{
    [Key]
    public int ContactID { get; set; }

    public string Phone { get; set; }
    public string Fax { get; set; }
    public bool IsDefault { get; set; }
    public int SerialNo { get; set; }
    public int AddressID { get; set; }

    //[ForeignKey("AddressID")]
    public virtual Addresses Addresses { get; set; } 

}

Db上下文

public class TestDBContext : DbContext
{
    public TestDBContext()
        : base("name=TestDBContext")
    {
        //((IObjectContextAdapter)this).ObjectContext.SavingChanges += new EventHandler(objContext_SavingChanges);
    }

    //public void objContext_SavingChanges(object sender, EventArgs e)
    //{
    //    var commandText = new StringBuilder();

    //    var conn = sender.GetType()
    //         .GetProperties(BindingFlags.Public | BindingFlags.Instance)
    //         .Where(p => p.Name == "Connection")
    //         .Select(p => p.GetValue(sender, null))
    //         .SingleOrDefault();
    //    var entityConn = (EntityConnection)conn;

    //    var objStateManager = (ObjectStateManager)sender.GetType()
    //          .GetProperty("ObjectStateManager", BindingFlags.Instance | BindingFlags.Public)
    //          .GetValue(sender, null);

    //    var workspace = entityConn.GetMetadataWorkspace();

    //    var translatorT =
    //        sender.GetType().Assembly.GetType("System.Data.Mapping.Update.Internal.UpdateTranslator");

    //    var translator = Activator.CreateInstance(translatorT, BindingFlags.Instance |
    //        BindingFlags.NonPublic, null, new object[] {objStateManager,workspace,
    //    entityConn,entityConn.ConnectionTimeout }, CultureInfo.InvariantCulture);

    //    var produceCommands = translator.GetType().GetMethod(
    //        "ProduceCommands", BindingFlags.NonPublic | BindingFlags.Instance);

    //    var commands = (IEnumerable<object>)produceCommands.Invoke(translator, null);

    //    foreach (var cmd in commands)
    //    {
    //        var identifierValues = new Dictionary<int, object>();
    //        var dcmd =
    //            (DbCommand)cmd.GetType()
    //               .GetMethod("CreateCommand", BindingFlags.Instance | BindingFlags.NonPublic)
    //               .Invoke(cmd, new[] { translator, identifierValues });

    //        foreach (DbParameter param in dcmd.Parameters)
    //        {
    //            var sqlParam = (SqlParameter)param;

    //            commandText.AppendLine(String.Format("declare {0} {1} {2}",
    //                                                    sqlParam.ParameterName,
    //                                                    sqlParam.SqlDbType.ToString().ToLower(),
    //                                                    sqlParam.Size > 0 ? "(" + sqlParam.Size + ")" : ""));

    //            commandText.AppendLine(String.Format("set {0} = '{1}'", sqlParam.ParameterName, sqlParam.SqlValue));
    //        }

    //        commandText.AppendLine();
    //        commandText.AppendLine(dcmd.CommandText);
    //        commandText.AppendLine("go");
    //        commandText.AppendLine();
    //    }

    //    System.Diagnostics.Debug.Write(commandText.ToString());
    //}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //modelBuilder.Configurations.Add(new vwCustomerConfiguration());
        Database.SetInitializer<TestDBContext>(null);
    }

    public DbSet<Customer> Customer { get; set; }
    public DbSet<Addresses> Addresses { get; set; }
    public DbSet<Contacts> Contacts { get; set; }
    public virtual DbSet<vwCustomer> vwCustomers { get; set; }
    public DbSet<vwMyCustomers> vwMyCustomers { get; set; }
}

public class MyLogger
{
    public static void Log(string component, string message)
    {
        Console.WriteLine("Component: {0} Message: {1} ", component, message);
    }
}

这样我就更新了mater并删除&amp;插入子数据

private void button3_Click(object sender, EventArgs e)
{
    //Addresses CurrentAddress = null;
    //Contacts CurrentContacts = null;

    using (var db = new TestDBContext())
    {
        //db.Database.Log = s => MyLogger.Log("EFApp", s);

        var existingCustomer = db.Customer
        .Include(a => a.Addresses.Select(x => x.Contacts))
        .FirstOrDefault(p => p.CustomerID == 5);

        existingCustomer.FirstName = "New Customer";

        existingCustomer.Addresses.Where(a => a.AddressID == 5).ToList().ForEach(r => db.Addresses.Remove(r));
        existingCustomer.Addresses.Where(a => a.AddressID == 5).SelectMany(ad => ad.Contacts).Where(c=> c.ContactID==5).ToList().ForEach(r => db.Contacts.Remove(r));

        Addresses oAdrModel = new Addresses();
        oAdrModel.Address1 = "New test xxx";
        oAdrModel.Address2 = "New test xxx";
        oAdrModel.SerialNo = 3;
        oAdrModel.IsDefault = true;
        oAdrModel.Contacts = new List<Contacts>();
        //oAdrModel.CustomerID = 5;
        existingCustomer.Addresses.Add(oAdrModel);
        //db.Addresses.Add(oAdrModel);
        //db.SaveChanges();
        //int CurAddressID = oAdrModel.AddressID;

        Contacts ContactModel = new Contacts();
        ContactModel.Phone = "New XX-1111111-33";
        ContactModel.Fax = "New XX-1-1111111";
        ContactModel.SerialNo = 4;
        ContactModel.IsDefault = true;
        //ContactModel.Addresses = oAdrModel;
        oAdrModel.Contacts.Add(ContactModel);

        //ContactModel.AddressID = CurAddressID;
        //db.Contacts.Add(ContactModel);

        db.SaveChanges();
    }
}

感谢