简体   繁体   English

实体框架:如何创建一种返回数据对象的方法?

[英]Entity Framework: How do I create a method to return data objects?

I have the following Method which returns a record based on the Primary Key passed as argument: 我有以下Method ,该Method基于作为参数传递的Primary Key返回一条记录:

class Program
{
    public static string GetRecord(Int64 pk)
    {
        using (var entityDataModel = new EntityDataModel())
        {
           var record = entityDataModel.Catalog.Find(pk);
           return record.VehicleMake;
        }
    }
    static void Main(string[] args)
    {
        Console.WriteLine(GetRecord(7341367950));
        Console.ReadKey();
    }
}

Instead of the above, I need the Method to return an object that exposes records depending on what Primary key I pass as argument by the caller: What data type can I use here? 代替上面的方法,我需要Method返回一个对象,该对象公开记录,具体取决于调用者作为参数传递给我的主键:在这里可以使用哪种数据类型?

Like this: (Example) 像这样:(示例)

   class Program
    {
        public static SomeDataType GetRecord(Int64 pk)
        {
            using (var entityDataModel = new EntityDataModel())
            {
                //Return record based on PK passed
               return entityDataModel.Catalog.Find(pk);
            }
        }
        static void Main(string[] args)
        {
            // Call the method here and return the data object
            var record = GetRecord(7341367950);

            Console.WriteLine(record.VehicleMake);

            //Or like this:

            Console.WriteLine(GetRecord(7341367950).VehicleMake);
            Console.ReadKey();
        }
    }

Update: Here is the Model: 更新:这是模型:

public partial class EntityDataModel : DbContext
{
    public EntityDataModel()
        : base("name=EntityDataModel")
    {
    }

    public virtual DbSet<Catalog> Catalog { get; set; }
    public virtual DbSet<Model> Model { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Catalog>()
            .Property(e => e.VehicleIdentificationNumber)
            .IsFixedLength();
    }
}

Answer: 回答:

I simply use the the Entity, in this case the Entity Model Catalog which represents a table in the database: 我只使用Entity,在这种情况下使用Entity Model Catalog,它代表数据库中的表:

    public static Catalog GetRecord(Int64 pk)
    {
        using (EntityDataModel entityDataModel = new EntityDataModel())
        {
            return entityDataModel.Catalog.Find(pk);
        }
    }


    static void Main(string[] args)
    {
        Catalog record = GetRecord(7341367950);
        Console.WriteLine(record.VehicleMake);

        Console.ReadKey();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM