English 中文(简体)
利用《第一号法典》(EntityFramework)获得非主要钥匙
原标题:Using Find in CodeFirst (EntityFramework) to get non-primary keys

My understanding is that find only takes the primary key as the parameter. That works great if the value you are looking for is actually the primary key. In my case, I have a class like this:

 public class Chamber
 {
    [Key]
    public int Id {get;set;}

    public string ChamberName { get; set; }
 }

我想检查一下,在我的情况或数据库本身中是否存在一个<代码>ChamberName。 我如何能够这样做? 我首先要看一下一下一下一下情况,然后在数据库中看到,有人叫db.Chambers.处(a=>a.ChamberName.equals.?

如果是<条码>,我会看到它运作良好。 ChamberName是我的主要关键,但不是。

THanks,

最佳回答

http://msdn.microsoft.com/en-us/library/gg696460%28v=vs.103%29.aspx”rel=“nofollow” 你们可以问,首先要找到符合具体情况的实体。

var entity = db.Chambers.Local.Where(/**/).SingleOrDefault();

if (entity == null)
{
   entity = db.Chambers.Where(/**/).SingleOrDefault();
}
问题回答

您可使用<代码>.Find()方法,但如何:

public Chamber FindByChamberName(string chamberName) 
{    
   using(MyDbContext ctx = new MyDbContext())
   {
      Chamber result = ctx.Chambers
                          .FirstOrDefault(c => string.Compare(c.ChamberName, chamberName, true));
      return result;
   }
}

你们不必人工列举任何东西——只是用该名称检索一间会议厅的头号——或无。

如果您需要了解某一分庭(以其<代码>ChamberName加以具体说明)是否存在,则您可在林克使用<代码>。

using(MyDbContext ctx = new MyDbContext())
{
    return ctx.Chambers.Any(c => string.Compare(c.ChamberName, chamberName, true));
}




相关问题
Entity Framework 4 Code First and the new() Operator

I have a rather deep hierarchy of objects that I m trying to persist with Entity Framework 4, POCO, PI (Persistence Ignorance) and Code First. Suddenly things started working pretty well when it ...

How do I verify my EF4 Code-Only mappings?

In NHibernate, there is a method doing something like ThisOrThat.VeryfyMappings() (I don t know the exact definition of it since it was a while ago I last tried NHibernate...) I recall seeing a blog ...

Using an Interface with a navigation property

I am trying to setup a project using Entity Framework 4, POCO, and Code-Only. Is it possible in entity framework for type of a navigation property to be an interface? I have a "Task" class. A Task ...

热门标签