NBear 里主子表设计方案
下面是主子表的创建脚本,在 NBear 里,能否实现如下操作:
Gateway.Default.Find<State>(State._.ID=”0310”).Citys
Gateway.Default.Find<City>(City._.ID=”0317”).State
即通过主表 State 来得到子表集合 , 能否通过子表得到主表对象 ??
答案如下:
public interface State : Entity
{
[PrimaryKey]
string ID { get; set; }
string Name { get; set; }
[FkQuery("Belong", OrderBy = "{ID} ASC", Contained = true, LazyLoad = true)]
City[] Citys { get; set; }
}
public interface City : Entity
{
[PrimaryKey ]
string ID {get;set;}
string Name {get;set;}
[FriendKey(typeof(State))]
[FkReverseQuery(LazyLoad = true )]
[MappingName("Belong")]
State Belong {get;set;}
}
if exists(select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_City_Belong_State]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
ALTER TABLE [dbo].[City] DROP CONSTRAINT FK_City_Belong_State
GO
if exists(select * from dbo.sysobjects where id = object_id(N'[dbo].[City]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[City]
GO
if exists(select * from dbo.sysobjects where id = object_id(N'[dbo].[State]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[State]
GO
CREATE TABLE [dbo].[City](
[ID] varchar(50) NOT NULL,
[Name] varchar(50) NULL,
[Belong] varchar(50) NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[City] WITH NOCHECK ADD
CONSTRAINT [PK_City] PRIMARY KEY CLUSTERED
(
[ID]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[State](
[ID] varchar(50) NOT NULL,
[Name] varchar(50) NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[State] WITH NOCHECK ADD
CONSTRAINT [PK_State] PRIMARY KEY CLUSTERED
(
[ID]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[City] ADD CONSTRAINT [FK_City_Belong_State] FOREIGN KEY ( [Belong] ) REFERENCES [dbo].[State]( [ID] ) NOT FOR REPLICATION
GO
insert into dbo.[State]
select '0310', '河北'
insert into dbo.[City]
select '0317','沧州','0310'
union
select '0315','衡水','0310'
![]() |
作者:NewSea 出处:http://newsea.cnblogs.com/
QQ,MSN:iamnewsea@hotmail.com 如无特别标记说明,均为NewSea原创,版权私有,翻载必纠。欢迎交流,转载,但要在页面明显位置给出原文连接。谢谢。 |