条件为假时如何保持现有数据不变

时间:2018-11-19 09:38:07

标签: c# sql-server database wpf

我目前正在从事一个项目,该项目需要能够将卡车租赁给客户,但是还需要添加客户详细信息(如果不存在)。我的问题是,即使我通过WPF表单输入了与客户完全相同的详细信息,也会添加一组新的数据,从而为一个人创建了一个新的Customer ID。我如何能够不考虑现有客户详细信息而获取数据库?

我的数据服务代码:

 public class DataService
{
    public static void rentTruck(TruckRental toRent, bool isNewCustomer)
    {
        using (var ctx = new DAD_TruckRental_RGMContext())
        {

            if (!isNewCustomer)
            {

                ctx.Entry(toRent.Customer).State = EntityState.Unchanged;//doesnt leave existing customer unchanged
            }
            ctx.Entry(toRent.Truck).State = EntityState.Modified;
            ctx.TruckRental.Add(toRent);
            ctx.SaveChanges();
        }
    }

我的CS代码:

private void Button_Click(object sender, RoutedEventArgs e)
    {

            TruckCustomer cust = new TruckCustomer();
            cust.Age = int.Parse(ageTextBox.Text);
            cust.LicenseNumber = licenseNumberTextBox.Text;
            cust.LicenseExpiryDate = licenseExpiryDateDatePicker.SelectedDate.Value.Date;


            TruckPerson per = new TruckPerson();
            per.Address = addressTextBox.Text;
            per.Telephone = telephoneTextBox.Text;
            per.Name = nameTextBox.Text;

            cust.Customer = per;


            int truckId = int.Parse(truckIdTextBox.Text);
            IndividualTruck truck = DataService.searchTruckByID(truckId);

            decimal priceTotal = decimal.Parse(totalPriceTextBox.Text);

            TruckRental toRent = new TruckRental();
            toRent.TotalPrice = priceTotal;
        toRent.RentDate = rentDateDatePicker.SelectedDate.Value.Date;

        toRent.ReturnDueDate = returnDueDateDatePicker.SelectedDate.Value.Date;
            toRent.Customer = cust;
            toRent.Truck = truck;
            truck.Status = "Rented";


            DataService.rentTruck(toRent, true);

            MessageBox.Show("Truck rented succesfully");


    }

1 个答案:

答案 0 :(得分:0)

这是我的建议

1-首先使用LicenseNumber检查数据库中是否存在客户详细信息 2-第一步将是null或具有详细信息,因此,如果为null,则添加收到的客户详细信息,否则更新

这是代码

public class DataService
{
    public static void rentTruck(TruckRental toRent, bool isNewCustomer, TruckCustomer tcustomer)
    {
        using (var ctx = new DAD_TruckRental_RGMContext())
        {
           var ob =  ctx.TruckCustomer.Where(c => c.LicenseNumber   == customer.LicenseNumber);
           if ( ob != null) //not exist 
            {

            //create new here 
            ctx.TruckCustomer.Add(tcustomer);
        }

        //exist then just update State
        ctx.ob.State = EntityState.Modified;
        ctx.AddOrUpdate(ob);
        ctx.TruckRental.Add(toRent);
        ctx.SaveChanges();
    }
}

我希望这可以为您提供帮助