导航属性/ Db外键 - 如何最好地设置?通过整数ID或通过对象引用? [英] Navigation Property / Db Foreign Key -- how best to set? via integer ID or via object reference?

查看:84
本文介绍了导航属性/ Db外键 - 如何最好地设置?通过整数ID或通过对象引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很抱歉,如果以前已经回答过 - 这是一个非常基本的事情。

My apologies if this has been answered before - it is a pretty basic thing.

我有一个简单的类,比如Product和ProductType,两者都映射到a数据库表。

I have a simple class, say Product and ProductType, both of which map to a database table.

如果在用户界面上,我希望用户创建新产品,并且在用户界面中,有一个下拉列表可选择"ProductType"。 - 编写逻辑来解决这些问题的最佳方法是什么?

If, on the UI, I want the user to create a new Product, and in the UI, there is a dropdown to select "ProductType" -- what is the best way to code the logic to hook these things up?

即。你做Product.ProductType = MyProductObj,还是可以做Product.ProductTypeId = 123?我想能够做任何一个,取决于代码工作流程(即如果来自UI,我不想重新检索对象来设置它。

i.e. do you do Product.ProductType = MyProductObj, or can you do Product.ProductTypeId = 123? I want to be able to do either one, depending on the code workflow (i.e. if coming from UI, I don't want to have to re-retrieve the object to set it.

我需要知道的任何事情,例如关于保存新对象,关于延迟加载等等?

Anything I need to know, e.g. with regards to saving a new object, with regards to lazy loading, etc.?

 

这是我的导航属性


    [Required]
    public int ProductTypeId
    {
      get { return _productTypeId; }
      set { _productTypeId= value; }
    }

    [Required]
    [ForeignKey("ProductTypeId")] 
    public ProductProductType
    {
      get { return _productType; }
      set { _productType = value; }
    }

推荐答案

我应该在LINQ2SQL中添加它,这就是我的做法(类似这样)

I should add that in LINQ2SQL, this is how I did it (something like this)


internal EntityRef<ProductType> _productType = new EntityRef<ProductType>();
[Association(ThisKey = "ProductTypeId", Storage = "_productType", OtherKey = "ProductTypeId", IsForeignKey = true)]
public ProductType ProductType
{
	get { return _productType.Entity; }
	internal set
	{
		if (value == null)
		{
			_productType = new EntityRef<ProductType>();
		}
		else
		{
			_productType.Entity = value;
		}
		ProductTypeId = (value == null ? 0 : value.Id.Value); // sync the integer Id property field
	}
}


这篇关于导航属性/ Db外键 - 如何最好地设置?通过整数ID或通过对象引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆