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

问题描述

不久,

这是一个架构

用户表

User Table

类别表

Category table

  1. 用户有一个 categoryID
  2. 我只需要用 User_ID、CategoryID、CategoryName
  3. 来填充 GridControl
  4. 注意,CategoryName 只属于第二个表(Category Table)

我所做的是:

Create Models (User,Category) 注意主键是复合的,所以它必须是结构 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;

结果:=失败

Result

我该怎么办?任何帮助

解决方法

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

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

并更改您的 CategoryName 属性:

[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));
    }
}  
,

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...