Об'єкт-запит (шаблон проєктування)

Об'єкт-запит (англ. Query Object) — шаблон проєктування, який дозволяє приховати SQL за допомогою об'єктів.

Опис

Використання мови запитів в коді призводить до того, що код стає тісно пов'язаним зі сховищем даним. Та при зміні структури сховища необхідно міняти код. Треба розв'язувати проблеми інкапсуляції схеми бази даних, підтримки роботи із декількома сховищами та оптимізації кількості запитів.

Рішенням буде створити інтерпретатор, який дозволить працювати зі сховищем як із колекцією об'єктів, та транслюватиме команди мовою запитів конкретного сховища.

Застосування

  • В Entity Framework даний шаблон реалізується через IQueryable.

Реалізація

Нехай у сховищі знаходяться об'єкти даного типу.

class User
{
	public int Id { get; set; }
}

Тоді примітивна реалізація цього шаблону матиме наступний вигляд.

interface IQueryableObject<T>
{
	IQueryableObject<T> Where(Expression<Predicate<T>> predicate);
	T[] ToArray();
}

class UserTable : IQueryableObject<User>
{
	private Expression<Predicate<User>> _predicate;

	public IQueryableObject<User> Where(Expression<Predicate<User>> predicate)
	{
		_predicate = predicate;

		return this;
	}

	public User[] ToArray()
	{
		var sql = BuildSql();

		// перегляд запиту
		Console.WriteLine(sql);

		return _db.Execute(sql);
	}

	private string BuildSql()
	{
		var predicate = BuildPredicate();

		return "SELECT * FROM Users " + predicate;
	}

	private string BuildPredicate()
	{
		var body = _predicate.Body as BinaryExpression;
		var leftParameter = (body.Left as MemberExpression).Member.Name;
		var rightParameter = (body.Right as ConstantExpression).Value;
		var operatorType = GetOperatorByType(body.NodeType);

		return $"WHERE {leftParameter} {operatorType} {rightParameter}";
	}

	private string GetOperatorByType(ExpressionType expressionType)
	{
		switch(expressionType)
		{
			case ExpressionType.Equal: return "=";
			case ExpressionType.GreaterThan: return ">";
				. . .
			default: throw new InvalidOperationException();
		}
	}
}

У коді прихована структура сховища.

var userTable = new UserTable();
		
// даний виклик сформує наступний запит: SELECT * FROM Users WHERE Id > 5
var users = userTable.Where(user => user.Id > 5).ToArray();

Див. також

Джерела

Read other articles:

Indonesian hot and sweet beverage This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Bajigur – news · newspapers · books · scholar · JSTOR (January 2023) (Learn how and when to remove this template message) BajigurBajigur with bits of bread, palm sugar and young coconutCourseBeveragePlace of originIndonesiaRegi...

 

Para una lista y generalidades de ellas, véase Anexo:Áreas metropolitanas de México. Mapa de las áreas metropolitanas del país. Las áreas metropolitanas de México han sido tradicionalmente definidas como el grupo de municipios o ciudades que interactúan fuertemente entre sí, normalmente en torno a un núcleo ciudad.[1]​ En 2004, en un esfuerzo conjunto entre el CONAPO, el INEGI y la SEDESOL se acordó definir las áreas metropolitanas por primera vez.[2]​ El 19 de octubre...

 

American politician Cornelius T. JordanMember of the Virginia Senatefrom the 9th districtIn officeJanuary 12, 1916 – January 14, 1920Preceded byWilliam H. LandesSucceeded byF. Percy Loth Personal detailsBornCornelius Theodore Jordan(1855-12-30)December 30, 1855Salem, Virginia, U.S.DiedJanuary 28, 1924(1924-01-28) (aged 68)Miami, Florida, U.S.Political partyIndependentSpouseMary MoserAlma materRoanoke College Cornelius Theodore Jordan (December 30, 1855 – January 28, 1924) wa...

American musician (1948–2020) Ian Lawrence FinkelIan Finkel playing the xylophoneBackground informationBorn(1948-08-13)August 13, 1948Brooklyn, New York, U.S.DiedNovember 16, 2020(2020-11-16) (aged 72)New York City, U.S.Instrument(s)XylophoneSpouse(s)Cheryl Ann AllenMusical artist Ian Lawrence Finkel (August 13, 1948 – November 16, 2020) was an American musician specializing in the xylophone, author, and entertainer.[1][2] Early life and education Finkel was the son o...

 

Japanese entertainment holding company Bandai Namco Holdings Inc.Bandai Namco's headquarters in Minato, TokyoNative name株式会社バンダイナムコホールディングスRomanized nameKabushiki-gaisha Bandai Namuko HōrudingusuTypePublicTraded asTYO: 7832 (TOPIX 100 component)IndustryEntertainmentPredecessorsBandai Co., Ltd.Namco Ltd.FoundedSeptember 29, 2005; 18 years ago (2005-09-29)HeadquartersSumitomo Fudosan Mita Building, Minato, Tokyo, JapanArea servedWorldwide...

 

Ghanaian musical twin duo This biography of a living person needs additional citations for verification. Please help by adding reliable sources. Contentious material about living persons that is unsourced or poorly sourced must be removed immediately from the article and its talk page, especially if potentially libelous.Find sources: Tagoe Sisters – news · newspapers · books · scholar · JSTOR (February 2018) (Learn how and when to remove this template ...

2016 album by Cafêzz A major contributor to this article appears to have a close connection with its subject. It may require cleanup to comply with Wikipedia's content policies, particularly neutral point of view. Please discuss further on the talk page. (May 2019) (Learn how and when to remove this template message) Sol BoricuaStudio album by CafêzzReleased2016 (2016)ProducerEdgardo SierraCafêzz chronology Music & Friends(2014) Sol Boricua(2016) Released in 2016, Sol Boricua ...

 

2022 Spanish filmEternaFilm posterDirected byJuanma SayalongaDavid SainzScreenplay byJuanma SayalongaDavid SainzCinematographyPaloma RoussanovaEdited byJavi LeríaMusic byGata CattanaProductioncompaniesDiffferent EntertainmentVivaTodo FilmsCinnamon FactoryDistributed by39 EscalonesRelease dates 7 November 2022 (2022-11-07) (Seville) 2 March 2023 (2023-03-02) (Spain) CountrySpainLanguageSpanish Eterna is a 2022 Spanish documentary film directed by Juanma S...

 

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Welcome to Atlanta – news · newspapers · books · scholar · JSTOR (December 2015) (Learn how and when to remove this template message) 2002 single by Jermaine Dupri featuring LudacrisWelcome to AtlantaSingle by Jermaine Dupri featuring Ludacrisfrom the album Ins...

Diagram showing the proportion of a receptor bound to a ligand This article is about the Hill equation as an equation used in biochemical characterization. For other uses, see Hill differential equation. Binding curves showing the characteristically sigmoidal curves generated by using the Hill equation to model cooperative binding. Each curve corresponds to a different Hill coefficient, labeled to the curve's right. The vertical axis displays the proportion of the total number of receptors th...

 

South Korean footballer In this Korean name, the family name is Kim. Kim Do-yeon Personal informationDate of birth (1988-12-07) 7 December 1988 (age 35)Height 1.66 m (5 ft 5+1⁄2 in)Position(s) DefenderTeam informationCurrent team Hyundai Steel Red AngelsNumber 4Senior career*Years Team Apps (Gls)2010–2011 Seoul WFC 2012– Hyundai Steel Red Angels International career2005 South Korea U17 5 (0)2007 South Korea U20 5 (0)2007–2019 South Korea 83 (1) *Club domestic l...

 

  لمعانٍ أخرى، طالع القلعة (توضيح). قرية القلعة  - قرية -  تقسيم إداري البلد  اليمن المحافظة محافظة حجة المديرية مديرية أفلح اليمن العزلة عزلة الجوان والقطابية السكان التعداد السكاني 2004 السكان 15   • الذكور 8   • الإناث 7   • عدد الأسر 2   • عدد المساك...

American brand of meal replacement products Soylent Nutrition, Inc.TypePrivately held companyIndustryMeal replacementFounded2013; 10 years ago (2013)FounderRob RhinehartHeadquartersLos Angeles, California[1], United StatesKey peopleDemir Vangelov (CEO)ProductsSoylentWebsitesoylent.com Soylent is a set of meal replacement products in powder, shake, and bar forms, produced by Soylent Nutrition, Inc. The company was founded in 2013 and is headquartered in Los Angeles, C...

 

Part of a series on theCulture of KarnatakaEmblem of Karnataka History Political history of medieval Karnataka Unification of Karnataka Etymology Historical sites of North Karnataka Alupa dynasty. Kadamba dynasty. Chalukya dynasty. Rashtrakuta dynasty. Hoysala Empire. Western Ganga dynasty Vijayanagara: (Origin. Empire. Musicological nonet. Medieval city. Military. Haridasa. Battle of Raichur. Battle of Talikota) Sultanate: (Ahmadnagar. Berar. Bidar. Bijapur. Deccan. Golkonda) Kodagu:(History...

 

German painter Portrait of Arno Holz, 1916 Erich Büttner (7 October 1889 – 12 September 1936) was a German painter. From 1906 to 1911 he studied at the Unterrichtsanstalt des Kunstgewerbemuseums Berlin. In 1908 he became a member of Berlin Secession. Works Büttner's work is dominated by color and dynamic form of expressionism. In the 1920s he created a series of portraits of his friends and fellow artists including Lovis Corinth, George Grosz, Arno Holz and Heinrich Zille. He produced...

波号第二百二十九潜水艦 佐世保港内で着底した波二百一型潜水艦左から順に波218、波229、波230(1946年春頃、佐世保港)基本情報建造所 佐世保海軍工廠運用者  大日本帝国海軍艦種 潜水艦級名 波二百一型潜水艦艦歴計画 マル戦計画起工 1945年6月27日進水 1945年7月27日最期 1945年8月17日工程75%で工事中止その後 戦後遭難着底1946年12月解体終了要目(計画時)基準排水量...

 

Delhi Delhi ndi boma lina la dziko la India. Chiwerengero cha anthu: 16.314.838. Nkhaniyi ndi stub. Mungathe kuthandiza Wikipedia ndi kukulitsa izo.

 

Sporting event delegationUnited States at the2015 Pan American GamesIOC codeUSANOCUnited States Olympic CommitteeWebsitewww.teamusa.orgin Toronto, CanadaJuly 10–26, 2015Competitors623 in 37 sportsFlag bearer (opening)Kim RhodeFlag bearer (closing)Claressa ShieldsMedalsRanked 1st Gold 103 Silver 82 Bronze 80 Total 265 Pan American Games appearances (overview)1951195519591963196719711975197919831987199119951999200320072011201520192023 The United States competed at the 2015 Pan Amer...

Paghimo ni bot Lsjbot. Alang sa ubang mga dapit sa mao gihapon nga ngalan, tan-awa ang Desa Banjarsari. 7°34′54″S 111°33′40″E / 7.5818°S 111.5611°E / -7.5818; 111.5611 Desa Banjarsari Banjarsar Administratibo nga balangay Nasod  Indonesya Lalawigan Jawa Timur Administratibo nga balangay Desa Banjarsari Gitas-on 61 m (200 ft) Tiganos 7°34′54″S 111°33′40″E / 7.5818°S 111.5611°E / -7.5818; 111.5611 Timezone WIT (UTC...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!