Reputation: 2649
I have base class :
public class BaseEntity
{
public Guid Id { get; set; }
public int AutoId { get; set; }
public int Status { get; set; }
// NOT REQUIRED // START
public Guid? CreatedByUserId { get; set; }
public string CreatedComputerName { get; set; }
public DateTime CreatedDate { get; set; }
public string CreatedIP { get; set; }
public Guid? ModifiedByUserId { get; set; }
public string ModifiedComputerName { get; set; }
public DateTime? ModifiedDate { get; set; }
public string ModifiedIP { get; set; }
// NOT REQUIRED // END
}
I have classes that get inheritance by BaseEntity
.
In my database, some table has not to have these properties. ( NOT REQUIRED SECTION PROPERTIES )
If I don't put into table these properties in database, I got error naturally when project is started.
An unhandled exception occurred while processing the request.
SqlException: Invalid column name 'CreatedByUserId'.
Invalid column name 'CreatedComputerName'.
Invalid column name 'CreatedDate'.
Invalid column name 'CreatedIP'.
Invalid column name 'ModifiedByUserId'.
Invalid column name 'ModifiedComputerName'.
Invalid column name 'ModifiedDate'.
Invalid column name 'ModifiedIP'.
How can I mark these properties as optional.
Maybe there is this field in database, maybe there is not.
Upvotes: 1
Views: 972
Reputation: 2649
@S.Akbari
This fluent api gives me what i want.
modelBuilder.Entity<Parameter>(opt =>
{
opt.ToTable("Parameter");
opt.HasKey(x => x.Id);
opt.Property(x => x.AutoId).UseSqlServerIdentityColumn();
opt.HasAlternateKey(x => x.AutoId);
opt.Ignore("CreatedByUserId");
opt.Ignore("CreatedComputerName");
opt.Ignore("CreatedIP");
opt.Ignore("ModifiedByUserId");
opt.Ignore("ModifiedComputerName");
opt.Ignore("ModifiedDate");
opt.Ignore("ModifiedIP");
});
Upvotes: 0
Reputation: 39966
You can exclude that properties from you base class and move them to the derived class and then use the [NotMapped]
as an attribute of the derived class. So even if you map the BaseEntity
class to the table, the Discriminator
columns will not be created because the derived class has marked as [NotMapped]
:
[NotMapped]
class NotRequired : BaseEntity
{
// NOT REQUIRED // START
public Guid? CreatedByUserId { get; set; }
public string CreatedComputerName { get; set; }
public DateTime CreatedDate { get; set; }
public string CreatedIP { get; set; }
public Guid? ModifiedByUserId { get; set; }
public string ModifiedComputerName { get; set; }
public DateTime? ModifiedDate { get; set; }
public string ModifiedIP { get; set; }
// NOT REQUIRED // END
}
And if you still want to keep this properties in your base class you can apply NotMapped
attribute to a property which you don't want to create a column in a database table for:
[NotMapped]
public string CreatedComputerName { get; set; }
Upvotes: 1