gpt4 book ai didi

c# - 通过代码零或一关系映射

转载 作者:行者123 更新时间:2023-11-30 14:57:45 25 4
gpt4 key购买 nike

我有以下数据库结构,我无法更改:

CREATE TABLE Users (
ID INT NOT NULL IDENTITY(1,1),
PRIMARY KEY(ID)
)

CREATE TABLE UserAvatars (
UserID INT NOT NULL,
Width INT NOT NULL,
Height INT NOT NULL,

PRIMARY KEY(UserID),
FOREIGN KEY(UserID) REFERENCES Users(ID),
)

基本上,用户可以拥有零个或一个头像(我删除了列以简化示例)。

class User
{
public int ID { get; protected set; }

public UserAvatar Avatar { get; set; }
}

class UserAvatar
{
public User User { get; set; }
public int Width { get; set; }
public int Height { get; set; }
}

我正在使用以下映射:

class UserMapping : ClassMapping<User>
{
public UserMapping()
{
Id(x => x.ID, m => {
m.Generator(Generators.Identity);
});

OneToOne(x => x.Avatar);
}
}

class UserAvatarMapping : ClassMapping<UserAvatar>
{
public UserAvatar()
{
Id(x => x.User, m =>
{
m.Generator(Generators.Foreign<User>(u => u.ID));
});

Property(x => x.Width);
Property(x => x.Height);
}
}

但是,当尝试运行我的应用程序时,我得到一个 NHibernate.MappingException:

NHibernate.MappingException : Could not compile the mapping document: mapping_by_code----> NHibernate.MappingException : Could not determine type for: MyApp.Models.UserAvatar, MyApp, for columns: NHibernate.Mapping.Column(User)

我无法理解这个神秘的错误。

我如何完成一个 User 可以有零个或一个头像的映射?

最佳答案

根据 Radim Köhler 的指导,解决问题的最终类/映射:

class User
{
public int ID { get; protected set; }
public UserAvatar Avatar { get; set; }
}

class UserAvatar
{
public int UserID { get; protected set; }
public User User { get; set; }
public int Width { get; set; }
public int Height { get; set; }
}

具有以下映射:

class UserMapping : ClassMapping<User>
{
public UserMapping()
{
Id(x => x.ID, m => {
m.Generator(Generators.Identity);
});

OneToOne(x => x.Avatar, m =>
{
m.Cascade(Cascade.All);
m.Constrained(false);
});
}
}

class UserAvatarMapping : ClassMapping<UserAvatar>
{
public UserAvatar()
{
Id(x => x.UserID, m =>
{
m.Generator(Generators.Foreign<UserAvatar>(u => u.User));
});

OneToOne(x => x.User, m =>
{
m.Constrained(true);
});

Property(x => x.Width);
Property(x => x.Height);
}
}

关于c# - 通过代码零或一关系映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20363292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com