如何在 DevExpress XPO 类 中创建一对一关系?

How to create one to one relationship in DevExpress XPO classes?

很快,

这是一个架构

用户Table

类别Table

  1. 一个用户有一个类别ID
  2. 我只需要用 User_ID、CategoryID、CategoryName
  3. 填充 GridControl
  4. 请注意,CategoryName 仅属于第二个 table(类别 Table)

我做的是:

创建模型(用户,类别)注意主键是复合的,所以它必须是结构 https://supportcenter.devexpress.com/ticket/details/a2615/xpo-how-to-map-persistent-objects-to-database-tables-with-compound-or-composite-multi#

// Composite key must be a struct
public struct user_key
{
    [Persistent("user_brn")]
    public int user_brn { get; set; }
    [Persistent("user_num")]
    public int user_num { get; set; }
}

[Persistent("Users")]
public class User : XPLiteObject
{
    public User(Session session) : base(session) { }

    [Key, Persistent] 
    public user_key key;    // user_brn, user_num

    [Persistent("user_name")]
    public string user_name { get; set; }

    [Persistent("CategoryID")]
    public int CategoryID { get; set; }

    [NonPersistent, Association("user_category")]
    public Category Category
    {
        get; set;
    }

    [PersistentAlias("Category.CategoryName")]
    public string CategoryName { get; set; }            // I think it will work. But it doesn't
}


[Persistent("Category")]
public class Category : XPLiteObject
{
    public Category(Session session) : base(session) { }

    [Key, Persistent("CategoryID")]
    public int CategoryID { get; set; }

    [Persistent("CategoryName")]
    public string CategoryName { get; set; }

    private User _user;
    [NonPersistent, Association("user_category")]
    public User User { get; set; }
}

GridView 代码

 IDataLayer dal = 
 XpoDefault.GetDataLayer(MSSqlConnectionProvider.GetConnectionString(" 
 (local)", "testdb"), AutoCreateOption.DatabaseAndSchema);
 Session session = new Session(dal);
 XPCollection collection = new XPCollection(session, typeof(User));
 gridControl1.DataSource = collection;

结果:=失败

我该怎么办?任何帮助

在一对一关系中,表应具有相同的键。

在您的 User class 中,删除 属性 CategoryId 并更改您的 Category 属性 如下:

[Persistent("CategoryID")]
public Category Category
{
    get; set;
}

并更改您的类别名称 属性:

[PersistentAlias("Category.CategoryName")]
public string CategoryName 
{ 
    get
    {
        return (string)EvaluateAlias(nameof(CategoryName));
    }
}  

Category 返回到 User 的引用比较棘手,因为没有持久字段来支持它。您可以免费加入试试:

[PersistentAlias("[<User>][Category = '@This.CategoryID'].Single()")]
public User User 
{ 
    get
    {
        return (User)EvaluateAlias(nameof(User));
    }
}