自定义类型允许定义复杂的数据结构,可以根据需要组织和处理数据。
复合类型
复合类型类似于表的行。你可以创建一个复合类型来包含多个字段:
CREATE TYPE person AS (
id INTEGER,
name TEXT,
birthdate DATE
);
定义一个包含 id
、name
和 birthdate
字段的自定义类型 person
。
CREATE TABLE employees (
id SERIAL PRIMARY KEY,
personal_info person
);
employees
表有一个 personal_info
列,其数据类型是自定义的 person
类型。
INSERT INTO employees (personal_info)
VALUES (ROW(1, 'John Doe', '1985-06-15'));
SELECT
(personal_info).id AS employee_id,
(personal_info).name AS employee_name
FROM employees;
CREATE FUNCTION get_person_info(id INTEGER)
RETURNS person AS $$
BEGIN
RETURN QUERY SELECT id, name, birthdate FROM employees WHERE id = id;
END;
$$ LANGUAGE plpgsql;
SELECT * FROM get_person_info(1);
(如果是存的自定义类型,那么EFCore取数据的时候需要映射到具体类型)
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Birthdate { get; set; }
}
public class Employee
{
public int Id { get; set; }
public Person PersonalInfo { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>()
.Property(e => e.PersonalInfo)
.HasColumnType("person");
}
** 枚举类型**
枚举类型用于定义一组预定义的值:
CREATE TYPE mood AS ENUM ('happy', 'sad', 'neutral');
这个枚举类型 mood
允许的值是 'happy'
、'sad'
和 'neutral'
。
CREATE TABLE feedback (
id SERIAL PRIMARY KEY,
response mood
);
```sql
INSERT INTO feedback (response) VALUES ('happy');
SELECT * FROM feedback WHERE response = 'happy';
注意存和区的时候枚举是当成字符串处理的
public enum Mood
{
Happy,
Sad,
Neutral
}
public class Feedback
{
public int Id { get; set; }
public Mood Response { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Feedback>()
.Property(f => f.Response)
.HasConversion(
v => v.ToString(), // 将枚举值转换为数据库中的字符串
v => (Mood)Enum.Parse(typeof(Mood), v)) // 从数据库中的字符串转换为枚举值
.HasColumnType("mood"); // 设置列的 PostgreSQL 类型为枚举类型
base.OnModelCreating(modelBuilder);
}