Using a single table for a class hierarchy I would like to use a projection to flatten the hierarchy to present a list of results to the user.
Is there a way to do this using HQL or Criteria API without having to issue multiple separate queries or unions?
Classes
public class A {
public virtual long Id { get; set; }
}
public class B : A {
public virtual DateTime SomeDate { get; set; }
public virtual OtherEntity Other { get; set; }
}
public class C : A {
public virtual DateTime? SomeDate { get; set; }
public virtual string Description { get; set; }
}
public class D : A {
public virtual string Description { get; set; }
}
public class OtherEntity {
public virtual string Name { get; set; }
}
SQL Tables:
CREATE TABLE Items (
Id bigint NOT NULL PRIMARY KEY,
Kind char(1) NOT NULL,
SomeDate datetime NULL,
Description NULL
)
CREATE TABLE OtherEntity (
Id bigint NOT NULL PRIMARY KEY,
Name nvarchar(255) NOT NULL
)
Output projection:
public class ItemReport {
// From A.Id
public virtual long Id { get; set; }
// From B.SomeDate or C.SomeDate
public virtual DateTime? SomeDate { get; set; }
// From C.Description or D.Description
public virtual string Description { get; set; }
// From B.OtherEntity.Name
public virtual string OtherName { get; set; }
}
Related
I have two model classes:
public partial class customer
{
public string customer_id { get; set; } // Primary Key
public string customer_name { get; set; }
public string course_mobile { get; set; }
public List<customer_address> customer_addresses { get; set; }
}
public partial class customer_address
{
public string address_id { get; set; } // Primary Key
public string adreess { get; set; }
public customer customer { get; set; }
public string customer_id { get; set; } // Foreign Key
}
I get an error:
The entity type 'customer' requires a primary key to be defined.
So how it solve?
Datbase table structure
You need to add [Key] attrubute.
public partial class customer
{
[Key]
public string customer_id { get; set; } // Primary Key
public string customer_name { get; set; }
public string course_mobile { get; set; }
public List<customer_address> customer_addresses { get; set; }
}
public partial class customer_address
{
[Key]
public string address_id { get; set; } // Primary Key
public string adreess { get; set; }
public customer customer { get; set; }
public string customer_id { get; set; } // Foriegn Key
}
I have two model class as;
public class MessageDetailModel
{
[Key]
public int messageDetailsId { get; set; }
public MessageModel messageModel { get; set; }
public string detail { get; set; }
public int senderId { get; set; }
public int customerId { get; set; }
public string phone { get; set; }
public DateTime date { get; set; }
}
and
public class MessageModel
{
[Key]
public int messageId { get; set; }
public int senderId { get; set; }
public int customId { get; set; }
public bool ReadInfo { get; set; }
public virtual List<MessageDetailModel> MessageDetails { get; set; }
}
and it is my context class ;
public virtual DbSet<MessageDetailModel> messageDetails { get; set; }
public virtual DbSet<MessageModel> messages { get; set; }
public virtual DbSet<PersonModel> persons { get; set; }
public virtual DbSet<DirectoryModel> directory { get; set; }
I am trying to get messageId over MessageDetailModel but messageId returns as 0 and I have that error "Object reference not set to an instance of an object"
Console.WriteLine(k.messageModel.messageId); //( k is my var which gets from messagedetail model)
How can ı reach messageId over MessadeDetailModel
There is no current link between your two models that would represent a Foreign Key.
You'd need to do something like this for your model if you want a Foreign Key to link to the related object:
public class MessageDetailModel
{
[Key]
public int messageDetailsId { get; set; }
[ForeignKey("messageId")] // Added Data Annotation for the Foreign Key relationship
public MessageModel messageModel { get; set; }
public string detail { get; set; }
public int senderId { get; set; }
public int customerId { get; set; }
public string phone { get; set; }
public DateTime date { get; set; }
public int messageId { get; set; } // This would be your Foreign Key
}
I've added the messageId column to your MessageDetailModel to match the Primary Key column of your MessageModel as that's necessary for the link to form.
You would use the [ForeignKey("messageId")] Data Annotation above the variable for the MessageModel to determine what value it needs to use when finding the object you want.
I am trying to relate my Tables with ForeignKey and PrimaryKey on the other end. But now i will be using a ForeignKey which is not the primary for the said table. I was using [InverseProperty] but i think there's a bug with it since i've been looking around for hours already and all of them says the same thing about it.
Documents Table:
public class Document
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int DocumentId { get; set; }
public int ProjectId { get; set; }
public int DepartmentId { get; set; }
public int AuthorId { get; set; }
[NotMapped]
public virtual User Author { get; set; }
}
Users
public class User
{
[Key]
public int UserId { get; set; }
public int AuthUserId { get; set; }
public string DisplayName { get; set; }
[NotMapped]
[ForeignKey("AuthorId")]
public virtual Document Document { get; set; }
}
Context:
modelBuilder.Entity<User>(entity =>
{
entity.HasOne(u => u.Document)
.WithMany("AuthorId");
});
I am trying to use the solution they here, but no luck.
Any help would really be appreciated. Thanks!
But now i will be using a ForeignKey which is not the primary for the said table.
To do this you can use EF Core Alternate Keys feature. But first correct your model class set up as follows: (As you said a User will have multiple Document)
public class Document
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int DocumentId { get; set; }
public int ProjectId { get; set; }
public int DepartmentId { get; set; }
public int AuthorId { get; set; }
public User Author { get; set; }
}
public class User
{
[Key]
public int UserId { get; set; }
public int AuthUserId { get; set; }
public string DisplayName { get; set; }
public ICollection<Document> Documents { get; set; }
}
Then in the Fluent API configuration as follows:
modelBuilder.Entity<Document>()
.HasOne(p => p.Author)
.WithMany(b => b.Documents)
.HasForeignKey(p => p.AuthorId)
.HasPrincipalKey(b => b.AuthUserId); // <-- here you are specifying `AuthUserId` as `PrincipalKey` in the relation which is not primary key
I am using ORMLite as my ORM and I am using it with following structure which contains the foreign key relation ship:
public class Order
{
[AutoIncrement]
public int Id { get; set; }
[Reference]
public Item Item { get; set; }
public string ProUserId { get; set; }
public string Details { get; set; }
}
public class Item
{
[AutoIncrement]
public int Id { get; set; }
public string Description { get; set; }
}
As we can see that Order contains the reference to the Item. In DB Order table has a foreign key called ItemId in the table and I have annotated that key in the design view with [Reference] attribute.
I am trying to save the Order with following code:
var order = new Order
{
Item = new Item
{
Id = 3,
Description = "Something"
},
ProUserId = "kunal#kunal.com",
Details = "fdfsdfsd"
};
Db.Save(order,references:true);
I was hoping that ORMLite would pick up the relationship and with ItemID in the Order table but it did not and it did throw following error instead:
Cannot insert the value NULL into column 'ItemId', table 'WebApp.dbo.Order'; column does not allow nulls. INSERT fails.
I tried changing my schema and addred OrderId column in my Item table with reference there and that works fine. But that is not the correct design. Should I make any changes in my code/schema to support this feature?
You still need to provide the foreign key that OrmLite can use to store the relationship, e.g. either on the Child/ForeignKey table:
public class Order
{
[AutoIncrement]
public int Id { get; set; }
[Reference]
public Item Item { get; set; }
public string ProUserId { get; set; }
public string Details { get; set; }
}
public class Item
{
[AutoIncrement]
public int Id { get; set; }
public int OrderId { get; set; } //Parent Table PK
public string Description { get; set; }
}
Or for 1:1 relationships, can be on the Parent table, e.g:
public class Order
{
[AutoIncrement]
public int Id { get; set; }
[Reference]
public Item Item { get; set; }
public int ItemId { get; set; } //Child Table PK
public string ProUserId { get; set; }
public string Details { get; set; }
}
public class Item
{
[AutoIncrement]
public int Id { get; set; }
public string Description { get; set; }
}
I am trying to build a Database from NHibernate mappings and have run into a problem.
I have many classes with localized string values:
public class MyClass1 {
public virtual int Id { get; set; }
public virtual ShortString Name { get; set; }
public virtual LongString Description { get; set; }
}
public class MyClass2 {
public virtual int Id { get; set; }
public virtual ShortString Name { get; set; }
public virtual LongString Description { get; set; }
}
and Languages like
public class Language {
public virtual string Code { get; set }
public virtual string Name { get; set }
}
My ShortString and LongString classes both look the same:
public class ShortString {
public virtual int Id { get; set; }
public virtual IDictionary<Language, string> Values { get; set; }
}
What I want to achieve are two tables (ShortString and LongString) looking like this:
TABLE ShortString
-----------------
Id (int)
LanguageCode (nvarchar(8))
Value (nvarchar(256)) (or ntext for the LongString Table)
...with Id AND LanguageCode as primary keys and a ForeignKey to the Language Table.
And in the MyClass1 and MyClass2 tables, I want to have NameId (int) and DescriptionId (int) columns mapped to ShortString and LongString tables respectively.
I am totally stuck. How can I achieve this?
Maybe you could ditch short and long string altogether
public class MyClass1 {
public virtual int Id { get; set; }
public virtual IDictionary<Language, string> Name { get; set; }
public virtual IDictionary<Language, string> Description { get; set; }
}
public class MyClass2 {
public virtual int Id { get; set; }
public virtual IDictionary<Language, string> Name { get; set; }
public virtual IDictionary<Language, string> Description { get; set; }
}
and use the folling Mapping
public class MyClass1Map : ClassMap<MyClass1>
{
public MyClass1Map()
{
[...]
HasMany(mc => mc.Name)
.Table("ShortString")
.KeyColumn("id")
.AsEntityMap("language_id")
.Element("value")
HasMany(mc => mc.Description)
.Table("LongString")
.KeyColumn("id")
.AsEntityMap("language_id")
.Element("value", e => e.Length(1000))
}
}
I cant test it right now so there might be tweaking nessesary