实体框架,仅添加记录后无法删除记录

时间:2018-07-26 08:38:42

标签: c# entity-framework

我正在制作一个使用数据库中一个表的简单WPF应用程序。我正在使用实体框架。这是我添加新记录的方式:

<?php
    session_start();
    include('config.php');

    $email = $_POST['elogin'];
    $password = $_POST['plogin'];
    $sql = "select * from student where email = '$email' and password = '$password' and status = 'enable'";
    $result = mysqli_query($con,$sql);
    $num_rows = mysqli_num_rows($result);
    if($result)
    {
        if ($num_rows > 0) 
        {
            $sqls = "select * from student where email = '$email' and password = '$password'";
            $results = mysqli_query($con,$sqls);
            while ($rows = mysqli_fetch_assoc($results)) 
            {
                $_SESSION['student_id'] =  $rows["id"];

            }
            header ("Location: student/dashboard.php");
        }
        else 
        {
            echo "<p id='red'>Wrong email or password or may be your account not activated.</p>";
        }   
    }
?>

工作正常:记录出现在数据库中。

现在,我尝试根据其public static bool CreateNew(CustomerModel newCustomer) { var addCustomer = new Customer { ID = newCustomer.ID, Name = newCustomer.Name, Address = newCustomer.Address, City = newCustomer.City, Country = newCustomer.Country }; try { //_context.Customers.Add(addCustomer); _context.Entry(addCustomer).State = EntityState.Added; _context.SaveChanges(); return true; } catch { return false; } } 删除刚刚添加的记录:

ID

不起作用。

应用程序中的DbSet似乎不保存已添加到数据库中的条目。我该如何解决?

PS。客户类别是我的public static bool Delete(long id) { var cust = new Customer() { ID = id }; try { _context.Entry(cust).State = EntityState.Deleted; /*_context.Customers.Attach(cust); _context.Customers.Remove(cust);*/ _context.SaveChanges(); return true; } catch { return false; } } 实体,POCO是我用于应用程序的类别。 CustomerModel引用了_context实体框架使用的

1 个答案:

答案 0 :(得分:2)

试试看。使用Find这样的方法:

var cust = _context.Customers.Find(id); 
_context.Customers.Remove(cust);
_context.SaveChanges();