SqlEmbeddedAttribute Class
.NET Standard 2.x
Specifies that a property of the model class will use the specified raw SQL SELECT statement to load data.
Namespace: SnapObjects.Data
Assembly: SnapObjects.Data.dll
Inheritance Constructor
System.Attribute
Syntax
[AttributeUsage(AttributeTargets.Property)]
public class SqlEmbeddedAttribute : Attribute, ISqlEmbedded
Constructors
Name | Description |
---|---|
SqlEmbeddedAttribute(string rawSql) | Initializes a new instance of the SqlEmbeddedAttribute class. |
Properties
Name | Return Type | Description |
---|---|---|
ParamValue | string | Gets or sets the value of the parameter that is required when loading the data for the current property. |
RawSql | string | Gets the raw SQL SELECT statement that will be used to load the data for the current property. |
Examples
The following code example demonstrates how to use the SqlEmbedded
attribute. When a property in the model is applied with the SqlEmbedded
attribute, it indicates the value of that property comes from a SQL query.
Model: PersonSqlEmbedded
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using SnapObjects.Data;
namespace Appeon.ApiDoc.Models.School
{
[Table("Person", Schema = "dbo")]
public class PersonSqlEmbedded
{
[Key]
public int PersonID { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public DateTime? HireDate { get; set; }
public DateTime? EnrollmentDate { get; set; }
public string Discriminator { get; set; }
[SqlEmbedded("select sum(Grade) from StudentGrade " +
"where StudentID = @personid", ParamValue = "$PersonID"
)]
public decimal? SumGrade { get; set; }
}
}
Example Method:
using SnapObjects.Data;
using Appeon.ApiDoc.Models.School;
using System;
namespace Appeon.ApiDoc.SqlEmbeddedAttributeExamples
{
public class SqlEmbeddedAttributeExample
{
private SchoolContext _context;
public SqlEmbeddedAttributeExample(SchoolContext dataContext)
{
// Sets the data context.
_context = dataContext;
}
public void Example()
{
var mapper = _context.SqlModelMapper;
// Gets the person record whose PersonID = 2 from the database.
// IMPORTANT: IncludeAll() must be executed here, otherwise the raw SQL
// in SqlEmbedded will not be executed.
var person = mapper.LoadByKey<PersonSqlEmbedded>(2)
.IncludeAll()
.FirstOrDefault();
Console.WriteLine("PersonID: {0}, SumGrade: {1}", person.PersonID,
person.SumGrade);
/* The code produces the following output:
PersonID: 2, SumGrade: 7.50
*/
/* Internally generated T-SQL:
exec sp_executesql N'SELECT
[PersonID],
[LastName],
[FirstName],
[HireDate],
[EnrollmentDate],
[Discriminator]
FROM [dbo].[Person]
WHERE ([PersonID] = @p0)',N'@p0 int',@p0=2
exec sp_executesql N'select sum(Grade) from StudentGrade
where StudentID =@personid',N'@personid int',@personid=2
*/
}
}
}
Applies to
.NET Standard
2.x