سری بررسی SQL Smell در EF Core - استفاده از مدل Entity Attribute Value - بخش دوم
نویسنده: سیروان عفیفی
تاریخ: ۱۳۹۹/۰۵/۱۴ ۱۲:۳۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
CREATE TABLE EmployeeJsonAttributes ( Id int NOT NULL AUTO_INCREMENT, EmployeeId int NOT NULL, Attributes json DEFAULT NULL, PRIMARY KEY (Id), FOREIGN KEY (EmployeeId) REFERENCES EmployeeEav (Id) ON DELETE CASCADE )
INSERT INTO EmployeeJsonAttributes VALUES (
101,
'{
"name": "Jon",
"lastName": "Doe",
"dateOfBirth": "1989-01-01 10:10:10+05:30",
"skills": [ "C#", "JS" ],
"address": {
"country": "UK",
"city": "London",
"email": "jon.doe@example.com"
}
}'
)
INSERT INTO efcoresample.EmployeeJsonAttributes VALUES (
101,
JSON_OBJECT(
"name", "Jon",
"lastName", "Doe",
"dateOfBirth", "1989-01-01 10:10:10+05:30",
"skills", JSON_ARRAY("C#", "JS"),
"address", JSON_OBJECT(
"country", "UK",
"city", "London",
"email", "jon.doe@example.com"
)
)
) SELECT JSON_EXTRACT(Attributes, '$.address.country') as Country FROM EmployeeJsonAttributes WHERE EmployeeId = 101; -- Conutry -- "UK"
SELECT Attributes -> '$.address.country' as Country FROM EmployeeJsonAttributes WHERE EmployeeId = 101; -- Conutry -- "UK"
SELECT EmployeeId, Attributes ->> '$.DateOfBirth' AS BirthDate FROM EmployeeJsonAttributes WHERE Attributes ->> '$.DateOfBirth' > DATE_SUB(CURRENT_DATE(), INTERVAL 25 YEAR)
// Fluent API
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>(entity =>
{
entity.Property(e => e.Attributes).HasColumnType("json");
});
}
// Data Annotations
[Column(TypeName = "json")]
public string Attributes { get; set; } public class EmployeeJsonAttribute
{
public int Id { get; set; }
public virtual EmployeeEav Employee { get; set; }
public int EmployeeId { get; set; }
[Column(TypeName = "json")]
public string Attributes { get; set; }
} dbContext.EmployeeJsonAttributes.Add(new EmployeeJsonAttribute
{
EmployeeId = 101,
Attributes = JsonSerializer.Serialize(new
{
FirstName = "Sirwan",
LastName = "Afifi",
DateOfBirth = DateTime.Now.AddYears(-31)
})
});
dbContext.SaveChanges(); var employee = dbContext.EmployeeJsonAttributes.Find(201); Console.WriteLine(JsonSerializer.Deserialize<Employee>(employee.Attributes).DateOfBirth);