Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all articles
Browse latest Browse all 1698

Saving a record with foreign key only?

$
0
0

Hi guys! 

I've been trying to figure if I can save a record by foreign key only. Here is an example:

I have 3 classes:

public class Person
{
    public Person()
    {
         Link = new HashSet<Link>();
    }

    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public ICollection<Link> Link { get; set; }
}

public class Vehicle
{
    public Vehicle()
    {
         Link = new HashSet<Link>();
    }

    public int Id { get; set; }
    public string Plate { get; set; }
    public string State { get; set; }

    public ICollection<Link> Link { get; set; }
}

public class Link
{
    public string FirstName{ get; set; }
    public string LastName{ get; set; }
    public string Plate { get; set; }
    public string State { get; set; }
    public int PersonId { get; set; }
    public int VehicleId { get; set; }

    public Person PersonIdNavigation { get; set; }
    public Vehicle VehicleIdNavigation { get; set; }
}

I have existing Person and Vehicle and I want to Link them by their id.

Let's say I have a Person with with:

Id = 5,
FirsName = "John",
LastName = "Snow"

And a vehicle:

Id = 3,
Plate = "Test",
State = "California"

If I create a new Link:

var link = new Link()
{
    PersonId = 5,
    VehicleId = 3
};

And I save it in the DB with EF. Will the FirstName, LastName, Plate, State properties be autopopulated and saved in the DB or I need to do it manually?

Thanks!


Viewing all articles
Browse latest Browse all 1698

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>