I have three classes
public class Country
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public byte CountryID { get; set; }
public byte OfficialLangID { get; set; }
}
public class Language
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public byte LangID { get; set; }
}
public class Name
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public byte NameID { get; set; }
public bool isLanguage { get; set; } // true for language - false for country
public byte FK { get; set; } // FK=LangID or CountryID
}
Now I want to create Navigation properties:
Country.Name
Language.Name
Name.Language
Name.Country
I want to do it in this way for many reasons, one of them to search for all the names in one table without joining.
Please don't suggest another way,I want navigation properties for my way.
why you're doing it like this? putting a boolean field to check the type of the entity here doesn't make any sense? in the end, the ef framework will create 2 tables.
here is my approach:
public class Country
{
public byte Id {get;set;}
public string Name {get;set;}
public int LanguageId {get;set;}
}
public class Language
{
public byte Id {get;set;}
public string Name {get;set;}
// assuming that each language may have one or many countries
public ICollection<Country> Countries {get;set;}
}
ef core here will create the tables and the relations automatically. now if you see some code duplications (like I've understood), that the 2 entities use the same field types and names, here is what you can do
public abstract class EntityBase
{
public byte Id {get;set;}
public string Name {get;set;}
}
now inherit this abstract class to the entity class
public class Country : EntityBase
{
public int LanguageId {get;set;}
}
public class Language : EntityBase
{
public ICollection<Country> Countries {get;set;}
}
Related
Scenerio:
public class Department
{
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
public string Description { get; set; }
public DateTime CreatedOn {get; set; }
public string CreatedBy {get; set; }
}
public class TestItem
{
public int TestItemId { get; set; }
public string TestItemName { get; set; }
public Department Department { get; set; }
public int DepartmentId { get; set; }
public DateTime CreatedOn {get; set; }
public string CreatedBy {get; set; }
}
public class Patient
{
public int PatientId { get; set; }
public string PatientName { get; set; }
public DateTime CreatedOn {get; set; }
public string CreatedBy {get; set; }
}
the problem is that, every time I create a table I have to add those two columns repeatedly.
But I want like this-
public class EntryLog
{
public int EntryLogId { get; set; }
public DateTime CreatedOn {get; set; }
public string CreatedBy {get; set; }
}
public class Department
{
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
public string Description { get; set; }
public EntryLog EntryLog { get; set; }
public int EntryLogId { get; set; }
}
and so on...
class A { .. }
class B { .. }
But its creating problem [showing conflicts error with other table's foreign key] while creating a row for a Department or a Patient.
In EF core, there is Table Per Hierarchy (TPH) but in that case every table will be merged into a single table. But that doesn't give me any solution.
looking forward to expert's suggestion...
The bottom line is: use EntryLog as a base type and don't tell EF about it. It's easy enough to keep EF-core oblivious of the base type: only register the derived types. Doing so, EF-core will map your subtypes to their own tables, just as if they didn't have a common type.
Now EntryLog will no longer need an Id, and it should be abstract:
public abstract class EntryLog
{
public DateTime CreatedOnUtc { get; set; }
public string CreatedBy { get; set; }
}
Whether this is enough depends on your specific requirements. There are several possibilities.
1. No additional configuration
If you're happy with the default conventions EF will apply to the common properties, your done. CreatedOnUtc will be mapped to a DateTime2 column (in Sql Server) and CreatedBy to an nvarchar(max) column in each table for an EntryLog entity.
However, if you do need custom configurations --for example if you want to map CreatedBy to an nvarchar(50) column-- additional mapping instructions should be applied. And of course you still want to do the mapping of the common properties only once --which would also happen if you did map the base type in a TPH scheme. How to do that?
2. Data annotations in the base type
The easiest option is to add data annotations:
public abstract class EntryLog
{
public DateTime CreatedOnUtc { get; set; }
[MaxLength(50)]
public string CreatedBy { get; set; }
}
And that's all.
But there are dev teams that don't want to use data annotations for mapping instructions. Also, EF's fluent mappings offer more options than data annotations do. If data annotations don't fit the bill for whatever reason, fluent configurations must be applied. But still, you only want to configure the common properties only once. A viable way to achieve that is to use IEntityTypeConfigurations for each EntryLog and let each concrete configuration derive from a base class. This offers two more options.
3. The base class contains regular properties
Option 4 will make clear why I talk about "regular properties" here. This is what it looks like:
abstract class EntryLogConfiguration
{
public void ConfigureBase<TEntity>(EntityTypeBuilder<TEntity> builder)
where TEntity : EntryLog
{
// Just an example of how to configure a base property.
builder.Property(e => e.CreatedBy).HasMaxLength(50);
}
}
class DepartmentConfiguration : EntryLogConfiguration,
IEntityTypeConfiguration<Department>
{
public void Configure(EntityTypeBuilder<Department> builder)
{
builder.Property(p => p.DepartmentName).HasMaxLength(100);
ConfigureBase(builder);
}
}
And in the context:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfiguration(new DepartmentConfiguration());
}
4. Using shadow properties
Shadow properties is a new feature of EF-core.
Shadow properties are properties that are not defined in your .NET entity class but are defined for that entity type in the EF Core model. The value and state of these properties is maintained purely in the Change Tracker.
Let's suppose you want to have CreatedBy as a class property (because you want to show it in a UI) but only need CreatedOnUtc as a property that's set in the background and that shouldn't be exposed. Now EntryLog will look like this:
public abstract class EntryLog
{
public string CreatedBy { get; set; }
}
So the property CreatedOnUtc is gone. It has been moved to the base configuration as shadow property:
abstract class EntryLogConfiguration
{
public void ConfigureBase<TEntity>(EntityTypeBuilder<TEntity> builder)
where TEntity : EntryLog
{
builder.Property(e => e.CreatedBy).HasMaxLength(50);
builder.Property<DateTime>("CreatedOnUtc");
}
}
Now you can't set CreatedOnUtc directly, only through EF's change tracker. The best place to do that is in an override of SaveChanges in the context:
public override int SaveChanges()
{
foreach (var entry in ChangeTracker.Entries<EntryLog>())
{
entry.Property<DateTime>("UpdatedOnUtc").CurrentValue = DateTime.UtcNow;
}
return base.SaveChanges();
}
Of course, if UpdatedOnUtc was a regular property, this override would also come in handy, but you could just do
entry.Entity.CreatedOnUtc = DateTime.UtcNow;
I hope this will give you enough food for thought to figure out which option suits you best.
I am using EF version 6.1 and have a mapping problem:
class BasePoco
{
public Guid Id{get;set;}
}
class Student : BasePoco
{
public string Name;
}
public class UserBase : BasePoco
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string Photo { get; set; }
}
public class UserDetail : UserBase
{
public string MobileNumber { get; set; }
public string EmailID { get; set; }
}
public Enum UserType
{
Student = 1,
User=2
}
the Attendance class
public class Attendance
{
public class UserId {get;set;} // Can be either student or user
public UserType UserType {get;set;}
}
I need to mark attendance for Student as well as User in the same table.
The UserType would determine whether the Id is of a student or User and the primary key would be a combination of UserType and Id.
How can I accomplish this using EF code first approach.
Sorry you cant use multiple type over single property. You do understand, because EF run over metadata. Which use EF know metadata from model class. This is a problem. Attendance table foregin key is multiple table referance and Attendance model contains both model. You should create logical layer for check UserType and access correct model. For example
public class Attendance
{
public UserType userType {get;set;}
public Guid? UserId {get;set;}
public virtual User user {get;set;}
public Guid? StudentId {get;set;}
public virtual Student student {get;set;}
}
now layer class
public class AttendanceUserLayer
{
public static object GetUser(Attendance attendance) {
if (attendance.userType == UserType.User) {
return attendance.User;
} else {
return attendance.Student;
}
}
how to use
Attendance attendance = context.Attendance.FirstOrDefault();
var userOrStudent = AttendanceUserLayer.GetUser(attendance);
if you cannot use the type of object result, write interface both class and set return type that interface.
I have a POCO class
public class Main
{
public int ExstraColumn{ get; set; }
}
public class User : Main
{
[Key]
public int Id { get; set; }
public int? Age { get; set; }
}
public class News : Main
{
[Key]
public int Id { get; set; }
public int? ReadCount { get; set; }
}
now i want entity framework inserts only age column in user. But it gives invalid column name ExstraColumn
how to tell entity framework that ExstraColumn field is only special usage?
You can use the [NotMapped] attribute in the System.ComponentModel.DataAnnotations namespace.
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.schema.notmappedattribute(v=vs.110).aspx
Denotes that a property or class should be excluded from database
mapping.
I have an abstract class inherited in 3 POCO objects:
public abstract class BaseObject
{
public virtual int Id { get; set; }
}
public class Post : BaseObject
{
public string Name { get; set; }
public virtual ICollection<PostCategory> PostCategory { get; set; }
}
public class Category : BaseObject
{
public string Name { get; set; }
public virtual ICollection<PostCategory> PostCategory { get; set; }
}
public class PostCategory
{
[Key]
[Column("Id", Order = 0)]
public int PostId { get; set; }
[Key]
[Column("Id", Order = 1)]
public int CategoryId { get; set; }
public string Value { get; set; }
public virtual Post Post { get; set; }
public virtual Category Category { get; set; }
}
However, whenever I do 'add-migration' in Package Manager Console, I get error:
Schema specified is not valid. Errors: (30,6) : error 0019: Each
property name in a type must be unique. Property name 'Id' was already
defined.
Basically complaining the ColumnAttribute having same property name (Id property in PostCategory object).
I need the property name to be the same for creating generic class that is used in generic Repo class. That's why I have the Id in an abstract class. But, this gives me error on CF migration part. Is there a way to get around this?
Thanks!
The ColumnAttribute attribute, sets the name generated in the SQL server. Obviously the column Id cannot be generated twice.
Simply remove the ColumnAttributes, allowing the server to generate the PostCategory table peacefully.
I have these three models:
public class Equipment
{
public int ID { get; set; }
public string title { get; set; }
}
[Table("Vessels")]
public class Vessel:Equipment
{
public string Size { get; set; }
}
[Table("Tubes")]
public class Tube : Equipment
{
public string Pressure{ get; set; }
}
I want to show a list of Equipments with 2 columns title and type.
for example:
Title Type
------ -------
101-1 vessel
101-2 vessel
102-3 tube
I don't know how to make a discriminator column in Equipments to show the type of each equipments.
EDITED
If I have a discriminator in Equipment entity like:
public class Equipment
{
public int ID { get; set; }
public string title { get; set; }
public string type{ get; set; } //as discriminator
}
I can get the query in controller or repository like this:
var equipments=from e in db.Equipments
select e;
You cannot make discriminator column in terms of EF mapping - TPT inheritance doesn't support it because the discriminator is a subtable. You can try to use something like:
public abstract class Equipment
{
public int ID { get; set; }
public string title { get; set; }
[NotMapped]
public abstract string Type { get; }
}
and override Type property in subtypes to get the correct name. You will not be able to use that property in Linq-to-Entities queries because it is not mapped.