Entity Framework Core Two Objects as Primary Key




I have a model which is used for managing friend relationships. It looks as follows:



```
public class Relationship
{   
   [Required]
   public User User { get; set; }

   [Required]
   public User Friend { get; set; }

   [Required]
   public DateTimeOffset RelationshipInitializationDate { get; set; }
}    

```

Users will have multiple records for their ID and there will be multiple records with the same FriendID so defining either of these as a key is a no-go. I would like the key to be a composite between User and Friend but when I define it like this:



```
modelBuilder.Entity<Relationship>().HasKey(r => new { r.User, r.Friend });

```

I get an error that states: 



```
The property 'Relationship.User' is of type 'User' which is not supported by current database provider. Either change the property CLR type or ignore the property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

```

How should I go about this to create the primary key that will link with a user and friend object. I didn't have any issues with my other objects having typed properties and I don't have an issue if I add an arbitrary key to the Relationship model. Thanks in advance
The basic idea here is that your adding properties to the model that EF can use to make a relationship. Right you're trying to create a relationship of type `User` and that is creating an error. To assign a composite key each key needs to be a type compatible with a `Key` field, not a navigation property. So we add `UserId` and `FriendId` of type `int`, `string` or `GUID` etc. and create a relationship off those properties.



```
public class Relationship
{
    public User Friend { get; set; }

    public User User { get; set; }

    public int FriendId { get; set; }

    public int UserId { get; set; }

    public DateTimeOffset RelationshipInitializationDate { get; set; }
}

public class User
{
    public int UserId { get; set; }
}

```

You can now define a composite key across `UserId` and `FriendId`. Something like this should do:



```
public class NorthwindContext : DbContext
{
     public NorthwindContext(DbContextOptions<NorthwindContext> options):base(options) { }

     public NorthwindContext() { }

     protected override void OnModelCreating(ModelBuilder builder)
     {
         builder.Entity<Relationship>().HasKey(table => new {
         table.FriendId, table.UserId
         });
     }
     public DbSet<Relationship> Relationships { get; set; }
     public DbSet<User> Users { get; set; }
}

```

[Source: Medium - How To: Entity Framework Core relationships, composite keys, foreign keys, data annotations, Code First and Fluent API](https://medium.com/radzenhq/how-to-entity-framework-core-relationships-composite-keys-foreign-keys-data-annotations-code-f4b238086463)
I don't know if this actually solves your issue, but I had the same problem and tried pretty much every solution out there.


Eventually, after installing the correct packages to support VS2012, I also installed [Entity Framework 6 Tools for Visual Studio 2012 & 2013](http://www.microsoft.com/en-us/download/details.aspx?id=40762)


After doing so (and a restart of VS) the connection showed up in the Entity Data Model Wizard.


Hope it solves your issue as well. > 
> What attributes I have to attach to the CreatedDate and ModifiedDate properties to make them automatically populated by the server based on the above scenario?
> 
> 
> 


**Solution 1)**



```
namespace Joukyuu.Models
{
    public class Passage
    {
        public int PassageId { get; set; }
        public string Contents { get; set; }


        public DateTime CreatedDate { get; set; }
        public DateTime ModifiedDate { get; set; }

       public Passage()
       {          
         this.CreatedDate  = DateTime.UtcNow;
         this.ModifiedDate = DateTime.UtcNow;
       }
    }
}

```

and by edit you have to change/update it by your self!


**Solution 2)**


Custom attribute:



```
[SqlDefaultValue(DefaultValue = "getutcdate()")]
public DateTime CreatedDate { get; set; }

```

[Entity Framework 6 Code first Default value](https://stackoverflow.com/questions/19554050/entity-framework-6-code-first-default-value)


**Solution 3)**


with help of Computed:



```
[Required, DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime CreatedUtc { get; set; 


  "dbo.Products",
            c => new
                {
                    ProductId = c.Int(nullable: false, identity: true),
                    Name = c.String(),
                    CreatedUtc = c.DateTime(nullable: false, defaultValueSql: "GETUTCDATE()"),
                })
            .PrimaryKey(t => t.ProductId);

```

<https://andy.mehalick.com/2014/02/06/ef6-adding-a-created-datetime-column-automatically-with-code-first-migrations/>


**Solution 4)**
You can also do this with command interceptor by modifying manually the query.


**Solution 5)** 
Use Repository pattern to manage the data creation and set it by CreateNew 
This is my favour Solution!


<https://msdn.microsoft.com/en-us/library/ff649690.aspx>


**Solution 6)** 
just set it or get in in the UI or in your VM.







In **Entity Framework Core 1.0** easy:



```
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Passage>()
        .Property(b => b.CreatedDate )
        .HasDefaultValueSql("getdate()");
}

``` The object you are linking with was built with the option to use the static run-time libraries, whereas your DLL was (properly) built to use the DLL libraries. When you mix these you'll get complaints such as this.


Since Fortran objects don't care which library set is used (this is not true of C/C++), one option could be to set the Linker>Input property "Ignore all default libraries" (/NODEFAULTLIB) in your DLL project. You will then need to name the required libraries under Additional Dependencies. (You can use the dumpbin command on your DLL's object to see a list.)


If you can rebuild the external object, do so with the Fortran > Libraries > Disable default library search rules property set to Yes. Then you should be able to link it in without further issue.




[View solution in original post](/t5/Intel-Fortran-Compiler/Error-linking-to-external-obj-file/m-p/1144075#M138021) Using [reflection](/questions/tagged/reflection "show questions tagged 'reflection'") and [expression-trees](/questions/tagged/expression-trees "show questions tagged 'expression-trees'") you can provide the parameters and then call `OrderBy` function, Instead of returning `Expression<Func<Task, T>>` and then calling `OrderBy`.


Note that `OrderBy` is an extension method and has implemented in both `System.Linq.Enumarable` and `System.Linq.Queryable` classes. The first one is for [linq-to-objects](/questions/tagged/linq-to-objects "show questions tagged 'linq-to-objects'") and the latter is for [linq-to-entities](/questions/tagged/linq-to-entities "show questions tagged 'linq-to-entities'"). [entity-framework](/questions/tagged/entity-framework "show questions tagged 'entity-framework'") needs the expression tree of the query in order to translate it to SQL commands. So we use the `Queryable` implementation.


It can be done by an extension method(explanations added as comments):



```
public static IOrderedQueryable<TSource> OrderBy<TSource>(
       this IQueryable<TSource> query, string propertyName)
{
    var entityType = typeof(TSource);

    //Create x=>x.PropName
    var propertyInfo = entityType.GetProperty(propertyName);
    ParameterExpression arg = Expression.Parameter(entityType, "x");
    MemberExpression property = Expression.Property(arg, propertyName);
    var selector = Expression.Lambda(property, new ParameterExpression[] { arg });

    //Get System.Linq.Queryable.OrderBy() method.
    var enumarableType = typeof(System.Linq.Queryable);
    var method = enumarableType.GetMethods()
         .Where(m => m.Name == "OrderBy" && m.IsGenericMethodDefinition)
         .Where(m =>
         {
            var parameters = m.GetParameters().ToList();
            //Put more restriction here to ensure selecting the right overload                
            return parameters.Count == 2;//overload that has 2 parameters
         }).Single();
    //The linq's OrderBy<TSource, TKey> has two generic types, which provided here
    MethodInfo genericMethod = method
         .MakeGenericMethod(entityType, propertyInfo.PropertyType);

    /*Call query.OrderBy(selector), with query and selector: x=> x.PropName
      Note that we pass the selector as Expression to the method and we don't compile it.
      By doing so EF can extract "order by" columns and generate SQL for it.*/
    var newQuery = (IOrderedQueryable<TSource>)genericMethod
         .Invoke(genericMethod, new object[] { query, selector });
    return newQuery;
}

```

Now you can call this overload of `OrderBy` like any other overload of it.  

For example:



```
var cheapestItems = _context.Items.OrderBy("Money").Take(10).ToList();

```

Which translates to:



```
SELECT TOP (10)  {coulmn names} FROM  [dbo].[Items] AS [Extent1] 
       ORDER BY [Extent1].[Money] ASC

```

This approach can be used to define all overloads of `OrderBy` and `OrderByDescending` methods to have `string` property selector. unfortunately that's not how it works. it's db mapping, and we're talking about joined-tables hierarchy. so the "other side" of the association must be in the referenced table (the detail one, not custom detail). that error happens when there's no handle to close. i see you call the 'open()' and you're not getting an object reference error before closehandle(). check your memory.pointerwrite() function to make sure it's not doing a closehandle() prematurely. it sounds like you're calling closehandle() twice. your link leads to an inactive developer message btw.

rest does not yet provide a way to list tags except by id. you can use the standard api with the same oauth2 access key that you would use for rest… using the data object you would want to query on the group table using the groupname field. RIA Services [is now OpenSource](http://jeffhandley.com/archive/2013/07/03/ria-services-is-getting-open-sourced.aspx) with the name "Open RIA Services" (see [on CodePlex](https://openriaservices.codeplex.com/)).


Colin Blair, the project leader, has just announced the first version with EF6 support :
<http://www.openriaservices.net/blog/post/The-Open-RIA-Services-Blog/1016/4-3-Alpha-NuGet-Packages-Released/>


You can install the Nuget package : [RIA Services for Entity Framework 6+](https://www.nuget.org/packages/RIAServicesContrib.EntityFramework).


~~If you want to install the Nuget package [RIA Services for Entity Framework 6+](https://www.nuget.org/packages/RIAServicesContrib.EntityFramework), be sure to select the "include prerelease" item in the top combo Box.~~ Presumably the Save button will already have the focus, so why not just use SendKeys


SendKeys "{Enter}"


HTH,  

Rob hi chris, 
if you use relations api, you may set properties field in your query. in this field you should set the names of the properties which values must be retrieved from the server. the argument should be a string in the following format: "propertyname1, propertyname2, , , propertynamen" , wher…