Last Updated
Viewed 56 Times
           

After my last question was to less detailed, I try to explain exactly, what problem I'm facing.

First an overview about all involved model classes:

public abstract class RecordBase 
{ 
    public int Id { get; set; }
}

public abstract class Record : RecordBase
{
    public DateTime CreateDate { get; set; }
    public int CreateUserId { get; set; }
    public virtual User CreateUser { get; set; }
}

public class User : RecordBase
{
    public string Username { get; set; }
}

public class Company : Record
{
    public string CompanyName { get; set; }
    public RecordReference FoundedByContact { get; set; }
}

public class Contact : Record
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}

public class RecordReference
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual RecordBase Record { get; set; }

    public RecordReference(RecordBase record)
    {
        Record = record;
        Id = record.Id;
        Name = record.ToString();
    }
}

The OnModelCreation method looks like this:

mb.Conventions.Remove<PluralizingEntitySetNameConvention>();
mb.Conventions.Remove<PluralizingTableNameConvention>();
mb.Conventions.Add<MappingInheritedPropertiesSupportConvention>();

mb.Entity<RecordBase>().Property(r => r.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

mb.Entity<Contact>().Map(r => {
    r.MapInheritedProperties();
    r.ToTable("Contacts");
});

mb.Entity<Company>().Map(r =>
{
    r.MapInheritedProperties();
    r.ToTable("Companies");
});

mb.Entity<User>().Map(r =>
{
    r.MapInheritedProperties();
    r.ToTable("Users");
});

When building the database script with Update-Database -Script, the table Companies is created together with an additional table RecordReference:

CREATE TABLE [dbo].[Companies] 
(
    [Id] [INT] NOT NULL IDENTITY,
    [FoundedByContact_Id] [INT],
    [CreateDate] [DATETIME] NOT NULL,
    [CreateUserId] [INT] NOT NULL,
    [CompanyName] [NVARCHAR](MAX),

    CONSTRAINT [PK_dbo.Companies] PRIMARY KEY ([Id])
)

CREATE TABLE [dbo].[RecordReference] 
(
    [Id] [INT] NOT NULL IDENTITY,
    [Name] [NVARCHAR](MAX),
    [Record_Id] [INT],

    CONSTRAINT [PK_dbo.RecordReference] PRIMARY KEY ([Id])
)

In addition there are multiple foreign keys and so on...which I don't need in this way.

I would like to achieve in this example, that the Companies-table is getting two additional fields like FoundedByContact_Id and FoundedByContact_Name to store the information.

The table RecordReferences is not needed for my purposes.

By the way - I'm using TPC that the database tables looks more "logical" if used for queries directly.

From the programming point of view, of course I could just remove all inheritance settings and don't care about the table design.

Basically the class RecordReference should just be used as a "custom property type" instead of creating 3 properties within company class.

The idea behind is to simplify a way to store the referenced records name in a DTO-using environment using Web Api and so on where the referenced record itself is not transmitted in all cases - but at least it's name should be available.

I hope, this time it's described as detailed as needed.

Thanks for any hint for a solution on this...

Regards Markus

Hi my first question here so forgive me if its not asked in the correct manner. I'm new to the entity framework and have a database first model.edmx file setup. What I would like to know is if there is a way to setup a property on an entity that returns a method: eg.I have a Customer entity with various properties. Using Linq I could do something like context.Customers.ToList(); to return all the customers. How could I create a property/method that would look like this context.Customers.getAll(); I could then create others like context.Customers.getVIP(); with cetain conditions.

Using an EF, Code First. In my class I have properties Quantity, Price and Amount. In setters of the first 2 properties I want to add logic to calculate amount. This works ok, but when I load entity next time, and Entity Framework fills properties with database values, than this custom logic is implemented too - and this is not good. How do you think is there any to implement custom logic only when user actually changes the value and not during object initialization?

This is something that worked up to now and now it just, stopped working (I know, weird, there's probably some silly mistake..)

I have a TripsVM, which contains a list of trips. I load these in my service, returning a List<>.

The problem occurs when I iterate over the trips collection and try to get trip.TripCategory.Name, as the TripCategory is empty, even though TripCategoryID has a value.

This all happens at the backend, I load the trips and then try to iterate over them, they are not being send from the page.

I could probably just load the trip by trip itself, but it used to work and this bug just came up after months of usage.

Any suggestions of where to look for bugs would be really appreciated.

Thanks

Error:

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Where error occurs:

foreach (Trip trip in tripsVM.TripsList) {
    var a = trip.TripCategory.Name;

TripsVM:

    private List<Trip> _TripsList;

    public List<Trip> TripsList
    {
        get
        {
            if (_TripsList == null)
            {
                _TripsList = TripsService.GetTrips();

                if (_TripsList == null)
                    _TripsList = new List<Trip>();
            }

            return _TripsList;
        }
        set { _TripsList = value; }
    }

Service:

public static List<Trip> GetTrips()
{ 
     return DB.Trips.Where(...).OrderBy(...).ToList(); 
}

Trip class:

public partial class Trip
{
    public int TripID { get; set; }
    public int TripCategoryID { get; set; }
    ....
    public virtual TripCategory TripCategory { get; set; }
}

Similar Question 4 (1 solutions) : Entity Framework Custom Navigational Properties

Similar Question 5 (1 solutions) : Entity Framework: Creating custom properties

Similar Question 7 (1 solutions) : Entity Framework - Loop through properties for update

Similar Question 8 (2 solutions) : Lower-casing the query generated by Entity Framework

cc