Peter Kellner
Peter Kellner

Reputation: 15478

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; }
 }

I want to check whether a given ChamberName exists in either my context or the database itself. How can I do that? Do I have to somehow enumerate of the context myself first, then, look it up in the database with a call like db.Chambers.where(a=>a.ChamberName.equals...?

I can see it working well if ChamberName is my primary key, but it is not.

THanks,

Upvotes: 3

Views: 5505

Answers (2)

Eranga
Eranga

Reputation: 32437

There is a property called Local in the DbSet. You can query that first to find entities loaded to the context.

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

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

Upvotes: 5

marc_s
marc_s

Reputation: 754210

You can't use the .Find() method - but how about:

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

You don't have to manually enumerate anything - just retrieve the first occurence of a chamber by that name - or none.

If you just need to know whether a given chamber (specified by its ChamberName) exists or not, you could use the .Any() method in Linq:

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

Upvotes: 2

Related Questions