简体   繁体   English

使用属性扩展 c# 中的类

[英]extend class in c# with properties

I use Entity framework 6 (database first) in my mvc project.我在我的 mvc 项目中使用实体框架 6(数据库优先)。 The database has a table called User which has columns like name, adress, email.该数据库有一个名为 User 的表,其中包含姓名、地址、电子邮件等列。 In my project I therefore have the User.cs class auto generated in my project.因此,在我的项目中,我在我的项目中自动生成了 User.cs 类。 I need to extend that user class with some properties.我需要使用一些属性扩展该用户类。 Should I create this in order to extend the class with this prpoerty..?我是否应该创建它以使用此属性扩展类..?

    public partial class User
{
    public bool SomeBoolProperty { get; set; }
}

If so where do I add it?如果是这样,我在哪里添加它? I tried to add it under a folder called partials\\user.cs but when doing so this property is not available when looking at what properties is available.我试图将它添加到名为 partials\\user.cs 的文件夹下,但是这样做时,在查看哪些属性可用时,此属性不可用。

You can have a child class derived from User class .您可以有一个从 User 类派生的子类。

Ex:前任:

public class childClass:User
{
   public bool SomeBoolProperty { get; set; }
}

You can access these property like this您可以像这样访问这些属性

User _user= new ChildClass();
_user.SomeBoolProperty =10;

It's possible that when you add the partial class in your "Partial" folder, Visual Studio adds .Partials to the namespace of the partial class you add, because the convention is that namespaces should follow the folder path.当您在“Partial”文件夹中添加.Partials类时,Visual Studio 可能会将.Partials添加到您添加的.Partials类的命名空间中,因为约定是命名空间应遵循文件夹路径。 In that case, the compiler won't join the auto-generated class with the partial class you created, because they are in different namespaces.在这种情况下,编译器不会将自动生成的类与您创建的分部类连接起来,因为它们位于不同的命名空间中。

Make sure the namespace is the same in your partial class and the generated class.确保您的分部类和生成的类中的命名空间相同。

You need to make sure that the namespace that you specify for your hand-written partial class User is exactly the sam e as that of the EF6-generated partial class User .您需要确保为手写partial class User指定的namespace与 EF6 生成的分部partial class Usernamespace完全相同 If the namespaces between the two are different then the partial classes will not be put together, they will stay separate.如果两者之间的命名空间不同,那么分部类将不会放在一起,它们将保持分开。

In your User.cs you can add properties that won't be mapped to the database by using the [NotMapped] attribute above your properties:在您的 User.cs 中,您可以使用属性上方的 [NotMapped] 属性添加不会映射到数据库的属性:

public class User
{
    //Your autogenerated properties

    [NotMapped]
    public bool SomeBoolProperty { get; set; }

    [NotMapped]
    public int AnotherProperty { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM