如何建立单向关系(数据库优先)

时间:2019-01-29 17:09:03

标签: sql-server entity-framework

我正在尝试向数据库中添加一个新表,该表与现有表具有一对多关系。在我的C#代码中,我希望这种关系是单向的(单导航),但它是双向的(完全定义)。

在此处调用表Customer和CustomerType。当前生成的模型如下:

当前型号:

public partial class Customer
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int CustomerTypeID { get; set; }  
    public virtual CustomerType CustomerType { get; set; }
}

public partial class CustomerType 
{
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Customer> Customers { get; set; }
}

并且我不想在生成的代码中包括CustomerType的Customers属性。

所需型号:

public partial class Customer
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int CustomerTypeID { get; set; }  
    public virtual CustomerType CustomerType { get; set; }
}

public partial class CustomerType 
{
    public int ID { get; set; }
    public string Name { get; set; }
}

我正在与一个现有的项目一起工作,因此这里要坚持采用数据库优先的方法,但是到目前为止,从谷歌搜索到现在,对于这个问题的数据库优先解决方案都是空的。要建立关系,我只是使用以下SQL查询向客户表添加了外键:

ALTER TABLE [dbo].[Customer]  WITH CHECK ADD FOREIGN KEY([CustomerTypeID])
REFERENCES [dbo].[CustomerType] ([ID])
GO

在数据库方面我可以做些什么来生成所需的输出吗?

0 个答案:

没有答案