多个模型的自定义数据模型

时间:2013-06-11 08:06:51

标签: asp.net-mvc entity-framework asp.net-mvc-4

我有3个不同的模型/表,每个都可以存储自定义字段。我的3个模型是Customer ProductStock

是否有创建映射到单个表的CustomData模型,可以处理所有3个模型的自定义数据?目前,我为每个模型都有一个单独的表/模型。

客户模式:

[Table("Customer")]
public class Customer
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CustomerID { get; set; }
    public string Prefix { get; set; }
    [Display(Name = "First Name")]
    public string FirstName { get; set; }
    [Display(Name = "Last Name")]
    public string LastName { get; set; }
    public string Address { get; set; }
    public string CountryID { get; set; }
    [ForeignKey("CountryID")]
    public virtual Country Country { get; set; }
    public string City { get; set; }
    [Display(Name = "Postcode")]
    public string PostCode { get; set; }
    //[RegularExpression(@"\b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}\b")]
    public string Email { get; set; }
    public string Remarks { get; set; }
    [Display(Name = "Telephone")]
    public string PhoneNumber { get; set; }
    public ICollection<CustomCustomerProperty> CustomProperties { get; set; }
}

产品型号:

[Table("Product")]
public class Product
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ProductID { get; set; }
    public int ProductTypeID { get; set; }
    public string ProductName { get; set; }
    [ForeignKey("ProductTypeID")]
    public virtual ProductType ProductType { get; set; }
    public ICollection<CustomProductData> CustomProperties { get; set; } 
}

自定义产品型号属性:

[Table("CustomProductData")]
public class CustomProductData
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CustomPropertyID { get; set; }

    public int CustomProductPropertyID { get; set; }
    [ForeignKey("CustomProductPropertyID")]
    public virtual CustomProductProperty CustomProductPropertyType { get; set; }

    public int ProductID { get; set; }
    [ForeignKey("ProductID")]
    public virtual Product Product { get; set; }

    public string PropertyValue { get; set; }
}

1 个答案:

答案 0 :(得分:0)

是的,你可以,但我认为目前的方法更好。无论如何,你应该扩展你的一个类来包含其他属性(也许是方法) - 在这种情况下,你的其他类的属性。

要执行此操作,请创建一个部分类,其中某个部分具有与其中一个实体类相同的名称和相同的程序集名称。

假设EF为您生成以下实体类:

namespace myPrj
{
    public partial class Product
    {
        // auto generated class
    }
}

现在,您创建一个如下所示的分部类:

namespace myPrj
{
    public partial class Product
    {
        // your partial class.
        // Add properties of other entity classes here
        // and you'll have all of them within the Product entity class...
    }
}
相关问题