1

我有两个 POCO 对象,Customer 和 CustomerAddress,如下所示。

public partial class Customer
    {
        public Customer()
        {
            this.CustomerAddresses = new HashSet<CustomerAddress>();
            this.Orders = new HashSet<Order>();
        }

        public int ID { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public System.DateTime DateOfBirth { get; set; }
        public byte Gender { get; set; }

        public virtual ICollection<CustomerAddress> CustomerAddresses { get; set; }
        public virtual ICollection<Order> Orders { get; set; }
    }

public partial class CustomerAddress
    {
        public int ID { get; set; }
        public int CustomerID { get; set; }
        public byte AddressType { get; set; }
        public string Street { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Country { get; set; }

        public virtual Customer Customer { get; set; }
    }

我正在创建一个新的 Customer 对象,如下所示。

Customer cust = new Customer();
            cust.ID = 9;
            cust.LastName = "Ross";
            cust.FirstName = "Taylor";
            cust.DateOfBirth = DateTime.Now;
            cust.Gender = 0;

            CustomerAddress custAdd = new CustomerAddress();
            custAdd.ID = 9;
            custAdd.Customer = cust;
            custAdd.AddressType = 0;
            custAdd.Street = "1 Main Street";
            custAdd.City = "Princeton";
            custAdd.State = "CA";
            custAdd.Country = "USA";

            DbConnection MyContext = new DbConnection(); ;
            MyContext.Customers.Add(cust);
            MyContext.CustomerAddresses.Add(custAdd);
            MyContext.SaveChanges();

我启动 SQL Profiler。保存此数据后,将针对数据库运行两个插入脚本,一个用于 Customer,另一个用于 CustomerAddress。但我的困惑是我在 SQL Profiler 中看不到任何 BEGIN TRANSACTION 和 COMMIT 语句。如果出于某种原因,为 CustomerAddress 插入脚本失败,我希望整个事务都失败,并且我不确定在没有 BEGIN TRANSACTION 的情况下是否会得到它。我在这里做错了什么吗?

4

0 回答 0