【问题标题】:How to get the ID from table by passing Name in Entity Framework in Silverlight mvvm?如何通过在 Silverlight mvvm 的实体框架中传递名称来从表中获取 ID?
【发布时间】:2012-12-13 08:09:27
【问题描述】:

在我的 Silverlight with MVVM 项目中,我使用的是实体框架。我有一张名为 Customer 的表,其中包含 CustomerID、Username、age 字段。我以编程方式插入了一行。

这里的CustomerID 字段是一个自动递增的字段。那么如何通过传递插入的UserName 来获取CustomerID 值呢?

需要 LINQ 查询以从实体框架中获取它..?

有什么帮助吗?

【问题讨论】:

    标签: silverlight entity-framework mvvm


    【解决方案1】:

    在调用SubmitChanges 之后,应在对象中设置自动递增的ID。也就是比如newId这里应该包含值:

    var customer = new Customer { Username = "test", Age = 100 };
    dataContext.InsertOnSubmit(customer);
    dataContext.SubmitChanges();
    var newId = customer.CustomerID;
    

    如果您需要随后从数据库中加载它,请使用简单查询:

    string name = "test";
    var customer = dataContext.Customers.Where(customer => customer.Username == test).FirstOrDefault();
    if (customer != null)
    {
        var newId = customer.CustomerID;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-03
      • 2012-12-15
      • 2018-12-12
      • 2013-10-16
      • 1970-01-01
      相关资源
      最近更新 更多