Entity Framework 4: Selecting Single Record

2019-01-14 16:25发布

问题:

I'm currently planning on switching my "manual query-writing" code to a nice SQL framework, so I can leave the queries or sql things to the framework, instead of writing the queries myself.

Now I'm wondering how I can get a single record from my table in Entity Framework 4?

I've primarily used SQL like SELECT * FROM {0} WHERE Id = {1}. That doesn't work in EF4, as far as I'm concerned.

Is there a way I can select a single ID-Based record from my Context?

Something like:

public Address GetAddress(int addressId)
{
    var result = from Context.Addresses where Address.Id = addressId;

    Address adr = result as Address;

    return Address;
}

Thank you!

回答1:

var address = Context.Addresses.First(a => a.Id == addressId);


回答2:

You can use Single or First methods.

The difference between those methods is that Single expects a single row and throws an exception if it doesn't have a single row.

The usage is the same for both of them



回答3:

(Based on VS 2015) If you create an .edmx (Add --> ADO.NET Entity Data Model).

Go through the steps to created the ".edmx" and use the following to run the stored procedure. emailAddress is the parameter you are passing to the stored procedure g_getLoginStatus. This will pull the first row into LoginStatus and status is a column in the database:

bool verasity = false;
DBNameEntities db = new DBNameEntities();   // Use name of your DBEntities

var LoginStatus = db.g_getLoginStatus(emailAddress).FirstOrDefault();

if ((LoginStatus != null) && (LoginStatus.status  == 1))
{
      verasity = true;
}