Pregunta

i have a SQL query (shown below), that i need to regularly run on 5 different pages. My question is, is there a way that i can write this once, and call it on each page (maybe using a function or a helper)?

    if(IsPost){
    var ImageCount = db.QueryValue("SELECT COUNT (*) FROM Property_Images WHERE PropertyID = @0", rPropertyId);
    var RateCount =  db.QueryValue("SELECT COUNT (*) FROM RateInfo WHERE PropertyID = @0", rPropertyId);
    var ExpiryDate = db.QueryValue("SELECT ExpiryDate FROM Property_Info WHERE PropertyID = @0", rPropertyId);


    if(ImageCount > 0 && RateCount > 0 && ExpiryDate > DateTime.Now){
        db.Execute("UPDATE Property_Info SET IsActive = 1 WHERE PropertyID = @0", rPropertyId);
    } else {
        db.Execute("UPDATE Property_Info SET IsActive = 0 WHERE PropertyID = @0", rPropertyId);
    }
    Response.Redirect(Request.RawUrl);
    }

I have used functions before to re-use SQL queries, but i have always assigned them as a 'bool', as the result is either true or force, but this isn't the case with this particular query. Any ideas?

¿Fue útil?

Solución

Methods can return void (or nothing). Your current code transcribed to a function might look like this:

@functions{
    public static void UpdateProperty(int propertyId, Uri url){
        var db = Database.Open("....");
        var ImageCount = db.QueryValue("SELECT COUNT (*) FROM Property_Images WHERE PropertyID = @0", propertyId);
        var RateCount =  db.QueryValue("SELECT COUNT (*) FROM RateInfo WHERE PropertyID = @0", propertyId);
        var ExpiryDate = db.QueryValue("SELECT ExpiryDate FROM Property_Info WHERE PropertyID = @0", propertyId);


        if(ImageCount > 0 && RateCount > 0 && ExpiryDate > DateTime.Now){
            db.Execute("UPDATE Property_Info SET IsActive = 1 WHERE PropertyID = @0", propertyId);
        } else {
            db.Execute("UPDATE Property_Info SET IsActive = 0 WHERE PropertyID = @0", propertyId);
        }
        HttpContext.Current.Response.Redirect(url);
    }
}

Then you would call it like this:

Is(IsPost){
    Functions.UpdateProperty(rPropertyId, Request.RawUrl);
}

Otros consejos

Cannot you use a SPROC instead? you could also return output parameters in case you need them

 string SQL = "exec dbo.myprocname @0";
 db.Execute(SQL, rPropertyId);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top